Sort ObservableCollection - what is the best approach?

前端 未结 1 1841
一整个雨季
一整个雨季 2020-12-30 04:32

I have a ObservableCollection , where MyData is a class with 4 properties i.e. int id, string name, bool IsSelected, string IsVisible.

This ObservableCollection is b

相关标签:
1条回答
  • 2020-12-30 05:14

    ICollectionView seems to be a perfect fit for this. It was designed specifically for sorting, filtering and grouping of a collection without modifying the original collection.

    You can get an instance of ICollectionView for your collection using the following code:

    var sortedCities  = CollectionViewSource.GetDefaultView(City);
    

    Then you can setup sorting by adding instances of SortDescription type to the ICollectionView.SortDescriptions collection:

    sortedCities.SortDescriptions.Add(new SortDescription("IsSelected", ListSortDirection.Descending));
    sortedCities.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
    

    Then you can bind your ComboBox directly to the collection view (instead of City collection) and it will display already sorted data.

    0 讨论(0)
提交回复
热议问题