[英]How To Grouping Data In WPF DataGrid
在我的WPF应用程序中,我要在此datagrid中使用datagrid,我想基于列名“ City”对数据库中的数据进行分组,我未使用mvvm体系结构和列表方法,而是在使用ICollectionView并将datatable对象作为一个参数,这是我的C#代码
ICollectionView cv = CollectionViewSource.GetDefaultView(dt);
cv.GroupDescriptions.Add(newPropertyGroupDescription("City"));
Hotels.ItemsSource = cv;
这是我的XAML代码:
<Window.Resources>
<Style x:Key="GroupHeaderStyle" TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<StackPanel>
<TextBlock Text="{Binding City}" Name="grouping" Foreground="Black"></TextBlock>
<ItemsPresenter/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<DataGrid Background="Azure" ItemsSource="{Binding Hotels}" CanUserAddRows="False" Name="Hotels" Style="{StaticResource AzureDataGrid}" Margin="0,173,0,0">
<DataGrid.GroupStyle>
<GroupStyle ContainerStyle="{StaticResource ResourceKey=GroupHeaderStyle}">
<GroupStyle.Panel>
<ItemsPanelTemplate>
<DataGridRowsPresenter/>
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>
编辑:
如果您没有为每个项目使用viewmodel,而是为DataTable的行对象使用了viewmodel,则WPF无法识别名称“ City”。 您需要使用组的名称,该名称由代表组项目的对象的CollectionViewGroupInternal.Name
属性持有。 在这种特定情况下,这就是城市的名称。 只需将Name
绑定到您的TextBlock。
使用组的HeaderTemplate,可以用更少的代码行实现目标。 默认ItemPresenter将在标题下方显示。
<!-- resources -->
<CollectionViewSource x:Key="devicesCollection" IsLiveSortingRequested="True" IsLiveGroupingRequested="True" Source="{Binding MyCollection}">
<!-- Sorting -->
<CollectionViewSource.SortDescriptions>
<componentModel:SortDescription PropertyName="Id" />
</CollectionViewSource.SortDescriptions>
<!-- Grouping -->
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="City"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
<DataTemplate x:Key="GroupingHeader">
<Border Background="Gray">
<TextBlock Margin="10 5 5 5" FontSize="12" FontWeight="Bold" Text="{Binding Name}"/>
</Border>
</DataTemplate>
<!-- data grid -->
<DataGrid ItemsSource="{Binding Source={StaticResource ResourceKey=devicesCollection}, Mode=OneWay}">
<DataGrid.GroupStyle>
<GroupStyle HeaderTemplate="{StaticResource ResourceKey=GroupingHeader}" />
</DataGrid.GroupStyle>
</DataGrid>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.