-->

Custom sorting logic for groups using CollectionVi

2019-05-05 23:02发布

问题:

I have a list of "stuff" which needs to be filtered then displayed in a grouped and sorted manner. The data needed to calculate the grouping and sorting order is not available as simple properties - there needs to be some work done in code to calculate the order and groups.

CollectionViewSource lets me define custom filter and sort logic - so far so good. It also lets me bind GroupDescriptions to a value converter so that I can generate the group names.

The last thing I want to do is control the order that the generated groups appear and this is causing me pain!

Everything I see about CollectionViewSource.SortDescriptions says that it will sort groups by a property name, but I don't have a property available to sort by. SortDescriptions can't be bound to a value converter like GroupDescriptions can and I'm out of other ideas.

So - how do you implement custom sorting logic of CollectionViewSource groups?

回答1:

This post on Bea Stollnitz' blog demonstrates how you can do that. You will have to sort by the criteria of your grouping first. Even if this is not a concrete property, it should be possible to sort your items using the same logic that you use to group them, isn't it?! Certainly, this is not possible using a SortDescription instance, but you could instead use the ListCollectionView.CustomSort property and specify an appropriate IComparer implementation.