tags:

views:

1574

answers:

2

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
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
`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
+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