本文介绍了在Datagrid WPF上对数据分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用一个扩展器将数据重新分组,该扩展器包含组名并且内部包含所有ClassMate名称。
I want to regroup my data with an expander that contains the group name and contains all ClassMate name inside.
这是我的班级Group:
This is my class Group :
public class Group{
public List<ClassMate> CLGroup { get; set; }
public string GroupName { get; set; }}
我的班级同班同学:
public class ClassMate: INotifyPropertyChanged{
public string Name { get; set; }
public string DisplayName { get; set; }}
我尝试使用此Xaml进行此操作,但我不知道为什么它不起作用
I tried to do this with this Xaml but I don't know why it's not working
<DataGrid x:Name="gridMates" ItemsSource="{Binding Groups }" >
<DataGrid.GroupStyle>
<!-- Style for groups at top level. -->
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True" >
<Expander.Header>
<DockPanel>
<TextBlock Text="{Binding Path=GroupName}" />
</DockPanel>
</Expander.Header>
<Expander.Content>
<ItemsControl ItemsSource="{Binding Path=CLGroup}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=DisplayName}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Expander.Content>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
我在做什么错?
谢谢
What am I doing wrong?Thanks
推荐答案
您需要绑定 ItemsSource
属性到分组的源集合。最简单的方法是使用 CollectionViewSource
:
You need to bind the ItemsSource
property to a grouped source collection. The easiest way to do this is to use a CollectionViewSource
:
<Grid>
<Grid.Resources>
<CollectionViewSource x:Key="groups" Source="{Binding Groups}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="GroupName" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</Grid.Resources>
<DataGrid x:Name="gridMates" ItemsSource="{Binding Source={StaticResource groups}}" AutoGenerateColumns="False">
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True" >
<Expander.Header>
<DockPanel>
<TextBlock Text="{Binding Path=Name}" />
</DockPanel>
</Expander.Header>
<Expander.Content>
<ItemsControl ItemsSource="{Binding Path=Items[0].CLGroup}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=DisplayName}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Expander.Content>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>
</Grid>
这篇关于在Datagrid WPF上对数据分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!