Kja*_*ara 3 c# wpf observablecollection
对于我的WPF项目,我需要一个可观察的集合,该集合始终保持正确的顺序。我的想法是使用SortedSet<T>和实现我自己的AddAndNotify和RemoveAndNotify方法。在其中,我会这样叫NotifyPropertyChanged:
public class ObservableSortedSet<T> : SortedSet<T>, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
public void AddAndNotify(T element)
{
Add(element);
NotifyPropertyChanged(...);
}
public void RemoveAndNotify(T element)
{
Remove(element);
NotifyPropertyChanged(...);
}
}
Run Code Online (Sandbox Code Playgroud)
但是那将是哪个属性?
如果集合内容发生更改,如何实现一个告诉UI进行更新的集合?
还是通过直接在ViewModel中使用SortedSet来获得更简单的方法?
编辑:
我不想将预定义ObservableCollection与排序视图一起使用。我知道可以通过使用CollectionViewSource或转换器来实现,但是这些解决方案对我而言并不有吸引力。我有CollectionViewSource无法使用的层次结构数据,并且我认为转换器版本对于的限制是一种可怕的解决方法CollectionViewSource。我想使用干净的解决方案。
因此,此问题不是如何对ObservableCollection进行排序的重复。我不想对进行排序ObservableCollection,而是想使用SortedSet可以告知用户界面更改的。
您应该改为实现INotifyCollectionChanged接口。
public class ObservableSortedSet<T> : SortedSet<T>, INotifyPropertyChanged, INotifyCollectionChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public event NotifyCollectionChangedEventHandler CollectionChanged;
public void NotifyPropertyChanged(string propName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
public void AddAndNotify(T element)
{
Add(element);
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add));
}
public void RemoveAndNotify(T element)
{
Remove(element);
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove));
}
}
Run Code Online (Sandbox Code Playgroud)