How can i add a header to a listview in xaml? I have this listview with a DataTemplate and cannot figure out how to get a header for the both text blocks.
<ListView Name="myListView" Grid.Row="2" IsItemClickEnabled="True" ItemClick="ListView_ItemClick" >
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate x:DataType="data:Thema">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<TextBlock FontSize="16" Text="{x:Bind Name}" VerticalAlignment="Center" Grid.Column="0" />
<TextBlock FontSize="16" Text="{x:Bind FachId}" VerticalAlignment="Center" Grid.Column="1" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The Listview gets its data from the c# code in the background: myListView.ItemsSource = tempThemen; It is a List with items in it.
I create Header Rows on my ListViews by defining ListView.HeaderTemplate.
<ListView.HeaderTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="8*" MinWidth="135"/>
<ColumnDefinition Width="15*" MinWidth="150"/>
<ColumnDefinition Width="3*" MinWidth="20"/>
<ColumnDefinition Width="2*" MinWidth="10"/>
</Grid.ColumnDefinitions>
<Border BorderBrush="AntiqueWhite" BorderThickness="0,0,0,0.5">
<TextBlock Text="Race Date" Margin="5,0,0,0" />
</Border>
<Border Grid.Column="1" BorderBrush="AntiqueWhite" BorderThickness="0,0,0,0.5">
<TextBlock Text="Circuit" Margin="5,0,0,0"/>
</Border>
<Border Grid.Column="2" BorderBrush="AntiqueWhite" BorderThickness="0,0,0,0.5">
<TextBlock Text="Laps" Grid.Column="2" Margin="0,0,5,0" HorizontalAlignment="Right"/>
</Border>
<Border Grid.Column="3" BorderBrush="AntiqueWhite" BorderThickness="0,0,0,0.5">
</Border>
</Grid>
</DataTemplate>
</ListView.HeaderTemplate>
Then I define the ListView.ItemTemplate with the same column definitions. After that, you'll notice that the ListViewItems have some padding and margins screwing up the alignment of the header and items. You can fix this in ListView.ItemContainerStyle like so:
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<ListViewItemPresenter ContentMargin="0" Padding="0" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With