WPF中Mvvm实现类似List的ObservableCollection在WPF中

摘自CSDN:

WPF中如果使用ObservableCollection,对ObservableCollection实现类似List的排序操作,再删除以后通知UI层刷新数据

public class SortableObservableCollection<T> : ObservableCollection<T>
{
  public SortableObservableCollection(List<T> list)
     : base(list)
  {
  }

  public SortableObservableCollection(IEnumerable<T> collection)
     : base(collection)
  {
  }

  public void Sort<TKey>(Func<T, TKey> 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<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer)
  {
     ApplySort(Items.OrderBy(keySelector, comparer));
  }

  private void ApplySort(IEnumerable<T> sortedItems)
  {
     var sortedItemsList = sortedItems.ToList();

     foreach (var item in sortedItemsList)
     {
        Move(IndexOf(item), sortedItemsList.IndexOf(item));
     }
  }
}

 使用集合分组:

//sort ascending
MySortableList.Sort(x => x.Name, ListSortDirection.Ascending);
//sort descending
MySortableList.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();            

 

posted @ 2013-04-24 16:55  qds86  阅读(904)  评论(0编辑  收藏  举报