I was having a look at the ObservableCollection code (thanks to the awsome .NET Reflector) and was surprised to find that the Add and Remove methods are not overriden. How then does ObservableCollection raise the PropertyChanged or CollectionChanged event to notify when something is added or removed?
+2
A:
It overrides a bunch of protected methods of the base Collection<T> class, e.g. InsertItem(int index, T item), RemoveItem(int index), etc.
These overrides specifically raise the events:
protected override void InsertItem(int index, T item)
{
this.CheckReentrancy();
base.InsertItem(index, item);
this.OnPropertyChanged("Count");
this.OnPropertyChanged("Item[]");
this.OnCollectionChanged(NotifyCollectionChangedAction.Add, item, index);
}
Damian Edwards
2010-08-26 16:54:38
DUH! thanks. I noticed that Collections.InsertItem was overridden but I failed to check that the base.Add method called the virtual InsertItem method.
Fragilerus
2010-08-26 17:05:27