我有一个 ObservableCollection ,其中 MyData 是一个具有 4 个属性的类,即 int id、字符串名称、bool IsSelected、字符串 IsVisible。
此 ObservableCollection 绑定(bind)到带有复选框的组合框(例如城市数据)。现在,当用户选中复选框时,然后下次打开下拉菜单时 - 所有选择都应按名称升序排列在顶部。
当用户在组合框中输入 3 个字符时,我还实现了自动完成,下拉菜单将首先打开显示所有选择,然后从用户输入的 3 个字符开始的所有项目。
我已经研究并实现了以下代码,它工作正常,但我想知道这是否是最好的方法,或者我可以以更好的方式实现它,代码是:
IEnumerable<MyData> sort;
ObservableCollection<MyData> tempSortedCities = new ObservableCollection<MyData>();
sort = City.OrderByDescending(item => item.IsSelected).ThenBy(item => item.Name.ToUpper()) ;
// City is my observablecollection<MyData> property in my Model binded to combobox in UI
foreach (var item in sort)
tempSortedCities.Add(item);
City.Clear(); // City is my observablecollection<MyData> property in my Model
City = tempSortedCities;
tempSortedCities = null;
sort = null;
在此先感谢您的时间 !
最佳答案
ICollectionView
似乎非常适合这个。它专为集合的排序、过滤和分组而设计,无需修改原始集合。
您可以获得 ICollectionView
的实例使用以下代码为您的收藏:
var sortedCities = CollectionViewSource.GetDefaultView(City);
然后您可以通过添加
SortDescription
的实例来设置排序。输入 ICollectionView.SortDescriptions
收藏:sortedCities.SortDescriptions.Add(new SortDescription("IsSelected", ListSortDirection.Descending));
sortedCities.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
然后你可以绑定(bind)你的
ComboBox
直接到 Collection View (而不是 City
集合),它将显示已排序的数据。
关于wpf - 排序 ObservableCollection - 最好的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5631110/