Hi, I've been trying to figure a way of grouping items in DataGrid in code-behind. My DataGrid is filled in code-behind from a List collection of custom Objects, what i wanted is to split this Objects in Groups. Thanks
A:
You can bind the DataGrid
to a CollectionView
that is created from your list of objects. The CollectionView
supports grouping. This is not really a code-behind solution, but it is very easy to use.
Martin Liversage
2009-08-18 14:02:57
I know how this can be done from xaml point of view, in my case this will not work as I'm building a custom control that extands to DataGrid class in order to style and organize data and functionality required.
Wizir
2009-08-18 14:07:38
`DataGrid` uses `ICollectionView` and `CollectionView` implements this interface. Maybe you can get some inspiration from the interactions between `DataGrid` and `ICollectionView`? You might implement your solution by implementing your own `ICollectionView` on your collection of objects.
Martin Liversage
2009-08-18 14:28:23
+1
A:
You do need to use a CollectionView, but the CollectionView base type does not support grouping.
To get grouping to work in code you need to use one of the derrived CollectionView types that implements grouping such as:
- ListCollectionView
- BindingListCollectionView
You use it something like this:
ListCollectionView lcv = new ListCollectionView(myCollection);
lcv.GroupDescriptions.Add(new PropertyGroupDescription("PropertyNameToGroupBy"));
MyDataGrid.ItemsSource = lcv;
Normally when you set a collection directly to the ItemSource, WPF will automatically create a CollectionView for you under the covers.
Bea Stollnitz talks a lot about CollectionViews on her blog if you want more info.
Schneider
2010-01-15 13:29:51