我在View中从ViewModel获取了一个ListCollectionView:
var collectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(ViewModel.Items);
然后按某些列进行分组和排序:
// group
collectionView.GroupDescriptions.Add(new PropertyGroupDescription("Index"));
// sort
collectionView.SortDescriptions.Add(new SortDescription("Index", ListSortDirection.Ascending));
collectionView.SortDescriptions.Add(new SortDescription("Key", ListSortDirection.Ascending));
它按预期方式工作(第一个组按索引排序,子项按Key字母排序。
现在,我想在IComparer的实现中使用自定义“键”排序,并且我尝试将CustomDeort与SortDescription一起使用,但是CustomSort确实清除了SortDescription(如果使用)。因此,只有CustomSort才能生效。
collectionView.CustomSort = new CustomItemKeyComparer(StringComparer.CurrentCulture);
collectionView.SortDescriptions.Add(new SortDescription("Index", ListSortDirection.Ascending));
那么如何在ListCollectionView中对多列排序使用CustomSort?
答案 0 :(得分:1)
您有两个选择。
您的CustomItemKeyComparer
类应包含根据 all 属性对项目进行排序的逻辑。
向数据项类添加另一个属性,该属性将基于自定义排序逻辑返回一个值,然后将另一个SortDescription
添加到集合视图中。
换句话说,您不应混用SortDescriptions
和CustomSort
。是一个或另一个,但不是两个。
答案 1 :(得分:0)
只需扩展@ mm8给出的答案和提供的第一个选项即可。
我将重写此博客中的一些代码,以创建支持多个列/属性的自定义IComparer:https://weblogs.asp.net/monikadyrda/wpf-listcollectionview-for-sorting-filtering-and-grouping
public class SortCreaturesByAgeAndFirstName : IComparer
{
public int Compare( object x, object y )
{
if( x as CreatureModel == null && y as CreatureModel == null )
{
throw new ArgumentException( "SortCreatures can
only sort CreatureModel objects." );
}
if( ((CreatureModel) x).Age > ((CreatureModel) y).Age )
{
return 1;
}
else if( ((CreatureModel) x).Age < ((CreatureModel) y).Age )
{
return -1;
}
else
{
// If the Age of the creatures are equal then sort by another property
return string.Compare(x.FirstName, y.FirstName);
}
}
}