转载:https://www.cnblogs.com/sjqq/p/8343335.html
wpf DataGrid 分组
//xaml
<Page.Resources>
<Style x:Key="GroupHeaderStyle" TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True">
<Expander.Header>
<TextBlock Text="{Binding Path=Name}" Background="Red"/>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
<DataGrid x:Name="dg" AutoGenerateColumns="True">
<DataGrid.GroupStyle>
<GroupStyle ContainerStyle="{StaticResource GroupHeaderStyle}">
<GroupStyle.Panel>
<ItemsPanelTemplate>
<DataGridRowsPresenter/>
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>
//Data
ObservableCollection<Stu> ss = new ObservableCollection<Stu>();
for (int i = 0; i < 30; i++)
{
Stu s = new Stu();
s.SName = "Name:" + i;
s.Sex = i % 2 == 0 ? "M" : "F";
s.Category = (i / 2) + "年级";
ss.Add(s);
}
//bind
ICollectionView view = CollectionViewSource.GetDefaultView(ss);
view.GroupDescriptions.Add(new PropertyGroupDescription("Category"));
dg.ItemsSource = ss;
//model
public string SName{get;set;}
public string Category{get;set;}
public string Sex{get;set;}
效果: