I have reason to wrap an instance of ObservableCollection<T>
in another type.
I'm implementing ICollection<T>
in my new type. That's straightforward. I'm also implementing INotifyCollectionChanged
, which means implementing
public event NotifyCollectionChangedEventHandler CollectionChanged;
The best path I can think of to implement this is to place additional code in my implementation of ICollection<T>
, like this:
public void Add(T item)
{
Collection.Add(item);
if (CollectionChanged != null) CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
}
(Collection is the instance of ObservableCollection<T>
that I am wrapping).
Is there a way to leverage the implementation of INotifyCollectionChanged
that Collection provides, rather than re-implementing it myself?
Yes. When you assign the value of your
Collection
property or field, handle its CollectionChanged event:Then in the HandleCollectionChanged method, you raise the object's own CollectionChanged event.