之前一直用的Dev的GridControl,控件自带分组排序啥的。今天试了下在wpf自带的Datagrid控件上实现分组和排序。
Datagrid上实现这些功能主要用到CollectionViewSource。CollectionViewSource有对数据进行分组和排序过滤的功能。
<CollectionViewSource x:Key="cvsList" Source="{Binding List}"
>
<CollectionViewSource.GroupDescriptions> <PropertyGroupDescription PropertyName="B"/>
</CollectionViewSource.GroupDescriptions>
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="B" Direction="Descending"/>
<scm:SortDescription PropertyName="E"/> </CollectionViewSource.SortDescriptions>
</CollectionViewSource>
将数据源绑定到CollectionViewSource,并设置分组列和排序列。倒序可以设置Direction属性为Descending
<DataGrid ItemsSource="{Binding Source={StaticResource cvsList}}" />
将CollectionViewSource绑定到DataGrid,并设置DataGrid的GroupStyle,分组功能就可以使用了。
下面是我的例子
<Window x:Class="DataGridTempalte.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DataGridTempalte"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800"> <Window.Resources> <CollectionViewSource x:Key="cvsList" Source="{Binding List}"
>
<CollectionViewSource.GroupDescriptions> <PropertyGroupDescription PropertyName="B"/>
</CollectionViewSource.GroupDescriptions>
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="B" Direction="Descending"/>
<scm:SortDescription PropertyName="E"/> </CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</Window.Resources> <Grid>
<DataGrid ItemsSource="{Binding Source={StaticResource cvsList}}" AutoGenerateColumns="False">
<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" Background="#FF112255" BorderBrush="#FF002255" BorderThickness="1,1,1,5"
>
<Expander.Header>
<DockPanel>
<TextBlock Foreground="White" FontWeight="Bold" Text="{Binding Path=Name}"/>
</DockPanel>
</Expander.Header>
<Expander.Content>
<ItemsPresenter />
</Expander.Content>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
<DataGrid.Columns>
<DataGridCheckBoxColumn Header="A" Binding="{Binding A}"/>
<DataGridTextColumn Header="B" Binding="{Binding B}"/>
<DataGridTextColumn Header="C" Binding="{Binding C}"/>
<DataGridTextColumn Header="D" Binding="{Binding D}"/>
<DataGridTextColumn Header="E" Binding="{Binding E}"/>
</DataGrid.Columns> </DataGrid> </Grid>
</Window>