For my WPF project I need an observable collection that always keeps the correct order. My idea is to use a SortedSet<T>
and implement my own AddAndNotify
and RemoveAndNotify
methods. In them, I would call NotifyPropertyChanged
, like this:
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(...);
}
}
But which property (or properties) would that be?
How can one implement a collection that tells the UI to update whenever the collection contents change?
Or is there an easier way by using the SortedSet directly in my ViewModel?
EDIT:
I don't want to use the predefined ObservableCollection
together with a sorted view. I know this is possible by using either CollectionViewSource
or converters, but these solutions don't appeal to me. I have hierarchichal data for which CollectionViewSource
doesn't work, and I consider the converter version a horrible workaround for the limits of CollectionViewSource
. I want to use a clean solution.
So this question is not a duplicate of how to sort ObservableCollection . I don't want to sort an ObservableCollection
, I want to use a SortedSet
that can tell changes to the UI.