I was trying to implement a specialized collection that works like ObservableCollection
to encapsulate some more mechanisms in it, to do that i also let my collection inherit from Collection
and i also implement the same interfaces.
I just do not get though how one actually implements the whole collection-changed-logic, for example Collection<T>.Add
is not being overridden (it is not even marked as virtual), so how does the ObservableCollection
fire the CollectionChanged
event if items were added using that method?
By default, you can use Add method to add a single item into ObservableCollection . To add a range of items, you can call the Add method multiple times using foreach statement.
Add(new Item() { ItemId = 1 }); // Also works for (int i = 1; i < 10; i++) { Items. Add(new Item() { ItemId = i }); } });
An ObservableCollection is a dynamic collection of objects of a given type. Objects can be added, removed or be updated with an automatic notification of actions.
The true difference is rather straightforward: ObservableCollection<T> implements INotifyCollectionChanged which provides notification when the collection is changed (you guessed ^^) It allows the binding engine to update the UI when the ObservableCollection is updated. However, BindingList<T> implements IBindingList .
To answer your specific question, Collection<T>.Add
calls the InsertItem
virtual method (after checking that the collection is not read-only). ObservableCollection<T>
indeed overrides this method to do the insert and raise the relevant change notifications.
It does so by calling InsertItem
which is overridden and can be seen upon decompilation
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With