Sunday, July 14, 2013

Advanced Usage of Grouping in CollectionView with ItemsPresenter

CollectionView is an object that we generally use while dealing with a collection in WPF. It is an object structure that supports a collection as well some of the inherent features which a user might always need while dealing with a collection. Some of the features like Sorting, Grouping, Filtering are automatically implemented in a CollectionView.  I have written one article on how to deal with CollectionView way back in Aug 2010 which explains almost everything you need to do while dealing with collection in WPF. But it does not give the entire story.

Controls that can show a Collection in WPF is somehow derived from ItemsPresenter. The ItemsPresenter has a property called ItemsSource which takes an object of ICollectionView, and hence it is one of the important interfaces considered so far.

There are some advanced scenarios where the general Grouping or sorting does not makes sense. Here in this article I am going to deal with such advanced scenarios which might be worth mentioning.

Advanced Grouping with CollectionView

Groping in ICollectionView is done by adding GroupDescription. Let us consider the case with some code:

ListCollectionView collectionView = new ListCollectionView(this.MyCollection);
collectionView.GroupDescriptions.Add(new PropertyGroupDescription("GroupProperty"));
return collectionView;

The ListCollectionView is an implementation of ICollectionView which allows you specify a GroupDescription on a Collection. Here in the above code, the MyCollection is an ObservableCollection that adds a GroupDescription on GroupProperty.

public class GroupedObjects
   // Other properties
    public string GroupProperty { get; set; }

QR: Inline image 1