一、目的:应用CollectionViewSource和GroupStyle设置DataGrid多级分组样式
二、实现
一级分组效果如下
二级分组效果如下
三、环境
VS2022
四、示例
具体实现代码如下
XML
<TabItem Header="DataGrid - 多级分组">
<TabItem.Resources>
<CollectionViewSource x:Key="cvs" Source="{h:GetStudents Count=10}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="Name" />
<PropertyGroupDescription PropertyName="Class" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</TabItem.Resources>
<DataGrid IsReadOnly="True" AutoGenerateColumns="False" ItemsSource="{Binding Source={StaticResource cvs}}">
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Margin" Value="0,0,0,5" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True">
<Expander.Header>
<DockPanel Margin="0 5">
<TextBlock Width="200"
Margin="5,0,0,0"
FontWeight="Bold">
<Run Text="厨师 :"/>
<Run Text="{Binding Name,Mode=OneWay}"/>
</TextBlock>
<TextBlock FontWeight="Bold">
<Run Text="数量 :"/>
<Run Text="{Binding ItemCount,Mode=OneWay}"/>
<Run Text="个"/>
</TextBlock>
</DockPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<DockPanel>
<DockPanel.Background>
<SolidColorBrush Color="Transparent" />
</DockPanel.Background>
<TextBlock Width="200"
Margin="30,6,0,6"
VerticalAlignment="Center">
<Run Text="班次 :"/>
<Run Text="{Binding Name,Mode=OneWay}"/>
</TextBlock>
<TextBlock VerticalAlignment="Center">
<Run Text="销量 :"/>
<Run Text="{Binding ItemCount,Mode=OneWay}"/>
<Run Text="单"/>
</TextBlock>
</DockPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</DataGrid.GroupStyle>
<DataGrid.Columns>
<DataGridTemplateColumn Width="Auto" Header="菜品">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="2.jpg" Width="200" VerticalAlignment="Center" Stretch="UniformToFill" Height="100"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Width="*" Header="产地" Binding="{Binding Address}"/>
<DataGridTextColumn Width="*" Header="邮箱" Binding="{Binding Emall}"/>
<DataGridTextColumn Width="100" Header="价格" Binding="{Binding Score, StringFormat={}{0:C}}"/>
<DataGridTextColumn Width="*" Header="联系方式" Binding="{Binding Tel}"/>
</DataGrid.Columns>
</DataGrid>
</TabItem>
首先,定义一个支持分组排序的CollectionViewSource资源
然后,绑定到DataGrid的ItemsSource上
最后,设置DataGrid的GroupStyle,示例中定义了二级分组,所以需要设置两个GroupStyle
五、需要了解的知识点
CollectionViewSource 类 (System.Windows.Data) | Microsoft Learn
GroupStyle 类 (System.Windows.Controls) | Microsoft Learn
六、源码地址
GitHub - HeBianGu/WPF-ControlDemo: 示例
GitHub - HeBianGu/WPF-ControlBase: Wpf封装的自定义控件资源库
GitHub - HeBianGu/WPF-Control: WPF轻量控件和皮肤库