I need to use a data grid and my data looks as follows: firstName, lastName, street, zip, city, country, image
In my datagrid I will only show firstName, lastName and image but it has to be grouped after city.
Update
The code below shows grouped items but the three items I want to display (firstName, lastName, image) are followed by all items (firstName, lastName, street, zip, city, country, image) per row. I think I have to replace the <ItemsPresenter />
but thats only speculation..
Can anyone help me, I can't manage this on my own...
<Grid>
<DataGrid ItemsSource="{Binding GroupedMovables}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Preview" Width="SizeToCells" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Name="Preview" Height="20" Source="{Binding Image}" HorizontalAlignment="Center" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="first name" Binding="{Binding FirstName}" />
<DataGridTextColumn Header="last name" Binding="{Binding LastName}" />
</DataGrid.Columns>
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=City}" FontWeight="Bold" Padding="3"/>
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander>
<Expander.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=ItemCount}" Margin="8,0,4,0"/>
<TextBlock Text="Element(s)"/>
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>
</Grid>
The proper way for grouping is to use a
CollectionView
(for more details: How to Navigate, Group, Sort and Filter Data in WPF). The following is a simple proof of concept application I created for you to show you how to use aCollectionView
for grouping you data:This class represents a row in the DataGrid:
MaindWindow code behind:
The DataGrid XAML code:
The result is:
For more information about styling the DataGrid groups please check this post: WPF DataGrid Control > Grouping