之前一直用的Dev的GridControl,控制項自帶分組排序啥的。今天試了下在wpf自帶的Datagrid控制項上實現分組和排序。 Datagrid上實現這些功能主要用到CollectionViewSource。CollectionViewSource有對數據進行分組和排序過濾的功能。 將數據源綁定到 ...
之前一直用的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>View Code