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

我只是一个虾纸丫 提交于 2019-12-12 22:58:01

问题


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?


回答1:


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...



来源:https://stackoverflow.com/questions/47519114/why-does-this-collectionviewsource-not-sort-on-the-enums-tostring-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!