Annoyances with ObservableCollection
August 12, 2009
Thought I’d share with you some of my gripes with the ObservableCollection<T> class that forms the basis of just about all data-bindable domain models in WPF and Silverlight.
Firstly why does it not support an AddRange(IEnumerable<T> items) method like other collections?
The EventHandler signature looks like:
private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
and NotifyCollectionChangedEventArgs has a property NewItems of type IList. This implies that you should be able to add multiple items, but the API doesn’t support it. Infuriating!
More importantly, when you Clear an ObservableCollection you get called on the CollectionChanged event with NotifyCollectionChangedAction.Reset. However when you look at e.OldItems you’d expect to find the list of items that were cleared, right? Sadly not. I often find that I hook into various event handlers in the OnCollectionChanged method. In order to clear these subscriptions on reset it means that I have to hold a parallel collection of the items in the ObservableCollection. Not good.
Also, why is there not an ObservableDictionary<TKey, TValue>? Various people have attempted to implement this, but it should really be part of the framework and understood by data binding.
I’m hopeful that these issues will go away with the BCL changes for the very groovy System.Reactive framework.