Trouble with BindableCollection (INPC.cs)

Topics: Framework Services
Jul 11, 2011 at 9:19 AM


I was only getting a    NotifyCollectionChangedAction.Reset event when using BindableCollection<T>

Looking at the code for AddRange and RemoveRange there is in both,

OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));

Just wondering it this is a cut & paste error, and there should be .Add and a .Remove usage?




Jul 11, 2011 at 9:24 AM

It is the proper implementation, since range operations (i.e. using Add/Remove actions with more than one item) are not supported by most parts of the WPF/Silverlight stack: you should get an InvalidOperation exception, stating that ranged operations are not supported (if I'm not wrong, raised by CollectionView or CollectionViewSource).

Jul 11, 2011 at 9:58 AM

Thanks for a speedy response

AddRange works fine - it implements a foreach!

But I don't even get an .Add event from the underlying ObservableCollection for each of the Adds. (which is orginally what I was expecting)

How odd. Perhaps it's a debugger/async issue.

Anyway, if it's right that's fine. Just that you can't tell the difference between an AddRange and a RemoveRange from the event!



Jul 11, 2011 at 10:10 AM
Edited Jul 11, 2011 at 10:11 AM

Exactly... if you need to register/unregister events from the collection (or perform a per-item operation on them), since after a reset you cannot determine what was added and what was removed (potentially, you cannot have a reference to the removed items), it is better to avoid Ranged operations completely... in my code I often forbid ranged operations or wrap them inside a standard foreach with multiple notifications.

Edit: note that the addition is performed without notification... so the underlying foreach does not raise an Add event, just a single Reset event once all the additions/removals are executed.