Click here to Skip to main content
15,501,747 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

            <RowDefinition Height="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
         <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" />

The following image displays what it looks like in Visual Studio 2017:[^]

You can see that even though the HeaderTemplate and ItemTemplate are defined the same way they layout 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?

What I have tried:

I changed the ItemTemplate ColumnDefinitions to look like the following:

    <ColumnDefinition Width="200" />
    <ColumnDefinition Width="*" />

That made it look much closer to the HeaderTemplate (as you can see in the following image).
But, i'm still not sure why they display differently.[^]
Updated 12-Dec-17 9:44am

1 solution

Apparently ListItems will not stretch to fill a space, but the Header item will.
To fix the problem you have to add the following to your ListView
    <Style TargetType="ListViewItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />

Then, you can change the Grid.ColumnDefinitions back to

  <ColumnDefinition Width="*" />
  <ColumnDefinition Width="Auto" />

Once you do that, the items will be stretched to fit just as the header items are.
Final result image which looks correct[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900