Search code examples
c#xamlwindows-10windows-10-mobile

C# XAML stretch grid to fit listViewItem


I have problems stretching grid to fit listViewItem. Although I set HorizontalContentAlignment to stretch, for some reason it always leaves blank space on each side. Here is an image of my app, purple color = grid, blue color = listViewItem. I want grid (purple color) to fit full width of item. I'd really appreciate if someone could tell me what I am doing wrong here.

enter image description here

MainPage.xaml

  <ListView x:Name="ListView" IsItemClickEnabled="True" SelectionMode="None" ItemClick="item_Clicked">
                <ListView.ItemContainerStyle>
                    <Style TargetType="ListViewItem" BasedOn="{StaticResource itemStyle}"/>
                </ListView.ItemContainerStyle>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Grid HorizontalAlignment="Stretch" Background="#FFFFD9D9">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition  Width="*" />
                            </Grid.ColumnDefinitions>
                            <TextBlock Text="{Binding time}" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Center"/>
                            <TextBlock Text="{Binding price}" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center"/>
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

App.xaml - resources

 <Application.Resources>
<Style x:Key="itemStyle" TargetType="ListViewItem">
    <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
    <Setter Property="VerticalContentAlignment" Value="Stretch"/>
    <Setter Property="Margin" Value="0,1,0,0"/>
    <Setter Property="Background" Value="Aquamarine"/>
</Style>


Solution

  • Try to set ContentMargin="0" for ListViewItemPresenter

      <Style TargetType="ListViewItem">
        <Setter Property="Template">
          <Setter.Value>
             <ControlTemplate TargetType="ListViewItem">
                  <ListViewItemPresenter ContentMargin="0" />
             </ControlTemplate>
         </Setter.Value>
        </Setter>
      </Style>