Search code examples
c#wpfsortingcollectionviewsource

Why does this CollectionViewSource not sort on the enum's ToString() result?


I have a view model that is used to produce items for an ItemsControl:

public class PermissionItemViewModel
{
    public PermissionsEnum Permission {get; set;}
}

The enum itself is defined in a way that the list is not naturally in alphabetical order, and when the control renders, the items are in the same order as the enum definition.

In my view, I am trying to define a CollectionViewSource and make it sort those items by what would essentially be myEnumValue.ToString(). Instead, the sort seems to be in order of the enum values instead of (what I thought would be) an implicit ToString() result.

<CollectionViewSource x:Key="permissionsViewSource"
                      Source="{Binding PermissionItems}">  <!-- ObservableCollection<PermissionItemViewModel> -->
    <CollectionViewSource.SortDescriptions>
        <cm:SortDescription PropertyName="Permission" />
    </CollectionViewSource.SortDescriptions>
</CollectionViewSource>

Ultimately, I use the source like this:

<ItemsControl ItemsSource="{Binding Source={StaticResource permissionsViewSource}}" />

I would like it to sort by the names of the enums, not their values. How can I force it to do that?


Solution

  • Looks like you may be able to grab the ListCollectionView and do a custom sort on that.

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        CollectionViewSource source = (CollectionViewSource)(this.Resources["MyCollectionViewSource1"]);
        ListCollectionView view = (ListCollectionView)source.View;
        view.CustomSort = new CustomSorter();
    }
    
    public class CustomSorter : IComparer
    {
        public int Compare(object x, object y)
        {
            var itemx = x as PermissionItemViewModel;
            var itemy = y as PermissionItemViewModel;
    
            return $"{itemx.Permission}".CompareTo($"{itemy.Permission}");
        }
    }
    

    You could salve your conscience a bit by writing this as an attached behavior for CollectionViewSource that would take a property name for its value. Offhand I think you'd want that to set up a property changed handler on View -- I think I wrote such a thing once, let's see if I can exhume it...