WPF中DataGrid进行分组
时间: 2023-11-30 17:02:32 浏览: 283
DataGridUC1.zip
可以通过在DataGrid中使用CollectionView来实现分组。具体步骤如下:
1. 在XAML中设置DataGrid的ItemsSource为CollectionView,并设置GroupDescription属性为分组依据的属性。
```
<DataGrid ItemsSource="{Binding Source={StaticResource myCollectionView}}">
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>
```
2. 在ViewModel中创建CollectionView,并设置其Source属性为数据源,设置GroupDescription属性为分组依据的属性。
```
public class MyViewModel
{
public ICollectionView MyCollectionView { get; set; }
public MyViewModel()
{
List<MyData> myDataList = new List<MyData>
{
new MyData { Name = "John", Age = 25, Gender = "Male" },
new MyData { Name = "Mary", Age = 30, Gender = "Female" },
new MyData { Name = "Tom", Age = 35, Gender = "Male" },
new MyData { Name = "Lucy", Age = 28, Gender = "Female" }
};
MyCollectionView = CollectionViewSource.GetDefaultView(myDataList);
MyCollectionView.GroupDescriptions.Add(new PropertyGroupDescription("Gender"));
}
}
public class MyData
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
```
以上代码会将数据按照Gender属性分组,显示在DataGrid中,每个分组的Header显示分组依据的属性值。
阅读全文