Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting CollectionViewSource using custom IComparer

Tags:

c#

wpf

I'm trying to sort a collection derived from CollectionViewSource, which simply has SortDescriptions for sorting. Unfortunately I need to be able to use my own custom IComparer, but I can't seem to find a way to do that. Think of a datagrid and I have my own multi-column sort algorithm. I'm thinking one way to do it is to use a collection implementing CollectionChanged that is an additional layer between the CollectionViewSource and my true datasource, but I would really prefer a better way if anyone has any suggestions.

like image 420
dariusriggins Avatar asked Jun 12 '09 19:06

dariusriggins


1 Answers

Bea Stollnitz has a custom sorting example here.

The key point of that article is to bind the CollectionViewSource to an IList implementation rather than a weaker ICollection or IEnumerable interface. With that, the View property returns a ListCollectionView instance instead of CollectionView. You can then use ListCollectionView.CustomSort to assign an IComparer to do your custom sorting. To make things easier, you can additionally use the Comparer<T>.Create method to use a Comparison delegate instead of a whole class.

like image 173
micahtan Avatar answered Oct 10 '22 11:10

micahtan