Search code examples
wpfsortinglistcollectionview

Sort ListCollectionView from second item down


In an MVVM environment, I have a ListCollectionView bound to an ObservableCollection. My Foo objects have a IsDefault property to them, and my requirement is to have that item first in the list, and the rest should be alpha-sorted.

So this code only sorts the whole list, obviously:

_list = new ListCollectionView(Model.Data);
        _list.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));

Not sure how to make sure that item #3 (for example, which has IsDefault=true) be at the top of the list, and the rest (that have IsDefault=false) be alpha sorted.

Is this a case to use _list.CustomSort and implement IComparer in some way?


Solution

  • Yes, this is exactly the case where you need to use ListCollectionView.CustomSort. Custom sorting is mutually exclusive with using SortDescriptions; the documentation for the former is explicit about this:

    Setting this property clears a previously set SortDescriptions value.

    So what you need to do is define an IComparer and use it to sort the view:

    class CustomComparer : IComparer
    {
        public int Compare (object lhs, object rhs)
        {
            // missing: checks for null, casting to Model.Data, etc etc
    
            if (lhsModelData.IsDefault && rhsModelData.IsDefault) {
                return lhsModelData.Name.CompareTo(rhsModelData.Name);
            }
            else if (lhsModelData.IsDefault) {
                return -1;
            }
            else if (rhsModelData.IsDefault) {
                return 1;
            }
            else {
                return lhsModelData.Name.CompareTo(rhsModelData.Name);
            }
        }
    }