zl程序教程

您现在的位置是:首页 >  后端

当前栏目

wpf DataGrid 分组

WPF 分组 Datagrid
2023-09-14 09:10:47 时间

转载: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;}

效果:
在这里插入图片描述
在这里插入图片描述