Annoyances with ObservableCollection

August 12, 2009

<rant>

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.

</rant>

Advertisements

2 Responses to “Annoyances with ObservableCollection”

  1. John Marks said

    […] 14, 2009 Following on from my woes about ObservableCollection<T>, and my annoyance at having to maintain a parallel collection to ensure all INotifyPropertyChanged […]

  2. […] 14, 2009 Following on from my woes about ObservableCollection<T>, and my annoyance at having to maintain a parallel collection to ensure all INotifyPropertyChanged […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: