摘自CSDN:
WPF中如果使用ObservableCollection,对ObservableCollection实现类似List的排序操作,再删除以后通知UI层刷新数据
public class SortableObservableCollection: ObservableCollection { public SortableObservableCollection(List list) : base(list) { } public SortableObservableCollection(IEnumerable collection) : base(collection) { } public void Sort (Func keySelector, System.ComponentModel.ListSortDirection direction) { switch (direction) { case System.ComponentModel.ListSortDirection.Ascending: { ApplySort(Items.OrderBy(keySelector)); break; } case System.ComponentModel.ListSortDirection.Descending: { ApplySort(Items.OrderByDescending(keySelector)); break; } } } public void Sort (Func keySelector, IComparer comparer) { ApplySort(Items.OrderBy(keySelector, comparer)); } private void ApplySort(IEnumerable sortedItems) { var sortedItemsList = sortedItems.ToList(); foreach (var item in sortedItemsList) { Move(IndexOf(item), sortedItemsList.IndexOf(item)); } }}
使用集合分组:
//sort ascendingMySortableList.Sort(x => x.Name, ListSortDirection.Ascending);//sort descendingMySortableList.Sort(x => x.Name, ListSortDirection.Descending);
如果你想实现类似数据源使用分组后对UI 层的通知可以参照:
string header = "HeaderName"; ListSortDirection direction; direction = ListSortDirection.Descending; ICollectionView dataView = CollectionViewSource.GetDefaultView(lv.ItemsSource); dataView.SortDescriptions.Clear(); SortDescription sd = new SortDescription(header, direction); dataView.SortDescriptions.Add(sd); dataView.Refresh();