I want to be able to add a range and get updated for the entire bulk.
I also want to be able to cancel the action before it's done (i.e. collection changing besides the 'changed').
Related Q Which .Net collection for adding multiple objects at once and getting notified?
Yes, adding your own Custom Observable Collection would be fair enough. Don't forget to raise appropriate events regardless whether it is used by UI for the moment or not ;) You will have to raise property change notification for "Item[]" property (required by WPF side and bound controls) as well as NotifyCollectionChangedEventArgs with a set of items added (your range). I've did such things (as well as sorting support and some other stuff) and had no problems with both Presentation and Code Behind layers.
Proof of need for
OnPropertyChanged("Count")
andOnPropertyChanged("Item[]")
calls in order to behave as perObservableCollection
. Note that I don't know what the consequences are if you don't bother!Here is a test method that shows that there are two PropertyChange events for each add in a normal observable collection. One for
"Count"
and one for"Item[]"
.@Shimmy , swap the standard for your collection and change to an add range and you will get zero PropertyChanges. Note that collection change does work fine, but not doing exactly what ObservableCollection does. So Test for shimmy collection looks like this:
FYI here is code from InsertItem (also called by Add) from ObservableCollection:
The C# summarized descendant.
More reading: http://blogs.msdn.com/b/nathannesbit/archive/2009/04/20/addrange-and-observablecollection.aspx
Please refer to the updated and optimized C# 7 version. I didn't want to remove the VB.NET version so I just posted it in a separate answer.
Go to updated version
Seems it's not supported, I implemented by myself, FYI, hope it to be helpful:
I updated the VB version and from now on it raises an event before changing the collection so you can regret (useful when using with
DataGrid
,ListView
and many more, that you can show an "Are you sure" confirmation to the user), the updated VB version is in the bottom of this message.Please accept my apology that the screen is too narrow to contain my code, I don't like it either.
VB.NET:
C#:
Update - Observable range collection with collection changing notification
I think AddRange is better implemented like so:
It saves you a list copy. Also if you want to micro-optimise you could do adds for up to N items and if more than N items where added do a reset.
You can also use this code to extend ObservableCollection:
Then you don't need to change class in existing code.