简体   繁体   English

与排序列表的数据绑定

[英]Data Binding with a Sorted List

My UI has a ListBox which is bound to a Collection.我的 UI 有一个绑定到 Collection 的 ListBox。 Right now this happens to be an ObservableCollection现在这恰好是一个 ObservableCollection

My objective is to add objects to this Collection via the UI, and have the ListBox dynamically update, all while maintaining a sorted Collection.我的目标是通过 UI 将对象添加到此集合中,并让 ListBox 动态更新,同时保持已排序的集合。

I am aware that there is some SortedView that I can use in WPF.我知道有一些 SortedView 可以在 WPF 中使用。 But that is not what I want - I need the actual Collection to remain sorted because my business logic requires a sorted collection.但这不是我想要的——我需要实际的 Collection 保持排序,因为我的业务逻辑需要一个排序的集合。

One way that I thought of, is to create my own Collection class which uses a SortedList internally, and implements the INotifyCollectionChanged interface and produces NotifyCollectionChangedEventArgs event when the internal list changes.我想到的一种方法是创建我自己的 Collection class,它在内部使用 SortedList,并实现 INotifyCollectionChanged 接口并在内部列表更改时生成 NotifyCollectionChangedEventArgs 事件。 Sounds like a lot of work!听起来工作量很大!

Is there a simple solution that I've missed?有没有我错过的简单解决方案?

Depending on your exact needs, the simplest approach is to keep your ObservableCollection, but wrap in in a new property of type ICollectionView:根据您的确切需求,最简单的方法是保留您的 ObservableCollection,但包含在 ICollectionView 类型的新属性中:

public class MyViewModel {
  private CollectionViewSource _collectionViewSource;

  public ICollectionView MyCollectionView  => _collectionViewSource.View;

  public MyViewModel(ObservableCollection<MyDataItem> dataItems) {
      _collectionViewSource = new CollectionViewSource() { Items = dataItems };
      //Add sorting here using _collectionViewSource.SortDescriptions.Add(...)
  }

You can use the wrapper property to extract a sorted list as needed.您可以根据需要使用 wrapper 属性提取排序列表。

Okay so I ended up inheriting from ObservableCollection, and overriding the Add() method.好的,所以我最终继承了 ObservableCollection,并覆盖了 Add() 方法。 This did the trick for me.这对我有用。 Now my list is always sorted, and the ObservableCollection is the one that Notifies the UI of changes.现在我的列表总是排序的,并且 ObservableCollection 是通知 UI 更改的列表。

   public class MyCollection : ObservableCollection<Int32>
   {
      public new void Add(Int32 x)
      {
         base.Add(x);
         var oldList = new ObservableCollection<Int32>(this.OrderBy(c=>c));

         Clear();
         foreach(var i in oldList)
         {
            base.Add(i);
         }
      }
   }

I'm a beginner with C#, any feedback on the code is appreciated.我是 C# 的初学者,感谢您对代码的任何反馈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM