문제

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:

Collection = new ObservableCollection<T>();
Collection.CollectionChanged += this.HandleCollectionChanged;

Then in the HandleCollectionChanged method, you raise the object's own CollectionChanged event.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top