1

I have a ListView on my form and I'm setting up the ListView.HeaderTemplate and it looks like what I expect it to look like.

However, if I copy the exact Grid definition into my ListView.ItemTemplate it does not layout the same.

items spaced differently

Altered Two Column Value Colors (Cyan and Green)

I have altered the color of the two Item column values so you can differentiate where each is showing up. I have two <x:String> values defined so data will show up in the preview layout of Visual Studio but when it runs the two layouts still look different even though they are defined the same.

No Grid.Row Defined On ItemTemplate TextBlocks

The one difference you'll notice in the XAML is that the ItemTemplate TextBlocks each only have its Grid.Column set (no Grid.Row set). That was a test and it looks the same either way.

Literally Copy / Pasted HeaderTemplate to ItemTemplate

I literally copied the HeaderTemplate to the ItemTemplate and made only the changes mentioned.

Why don't they layout the same?

<ListView.HeaderTemplate>
   <DataTemplate>
      <Grid>
         <Grid.RowDefinitions>
            <RowDefinition Height="*" />
         </Grid.RowDefinitions>
         <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
         </Grid.ColumnDefinitions>
         <TextBlock Margin="7 0 0 0" Grid.Row="0" Grid.Column="0" Foreground="#ff0000" Text="Date"  />
         <TextBlock Margin="0 0 15 0" Grid.Row="0" Grid.Column="1" Foreground="#ff0000" Text="Entry Count" />
      </Grid>
   </DataTemplate>
</ListView.HeaderTemplate>

EDIT

If I change the ItemTemplate ColumnDefinitions to look like the following:

<Grid.ColumnDefinitions>
    <ColumnDefinition Width="200" />
    <ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

Then it does get closer to what I expect, but I'm still not sure why I have to do this differently.

better layout

1 Answer 1

1

By default, ListViewItem won't stretch its content. Set HorizontalContentAlignment as Stretch in ItemContainerStyle.

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    </Style>
</ListView.ItemContainerStyle>
2
  • Method 1 worked perfectly. Where did you learn about ItemContainerStyle? I never would've found that if you hadn't shown me. Thanks very much. There seems to be much undocumented (or rarely documented) in XAML / UWP. BTW, Method 2 does not solve the problem. I tried it.
    – raddevus
    Dec 12, 2017 at 19:33
  • @raddevus ItemContainerStyle is a part of ItemsControl. Also, I think, It is safe to remove my disclaimer. Dec 12, 2017 at 19:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.