Freigeben über


Making sense of NotifyCollectionChangedEventArgs

I really like Data Binding in WPF. Combined with the separation of Behavior and Appearance it is incredible powerful.

But from time to time you want to implement your own collection class and that poses a slight challenge because you need implement to INotifyCollectionChanged. This interface is used by the Data Binding mechanism to figure out if and what has changed in the collection it binds to.

The challenge that I had a few times is, to figure out how to call the constructor of NotifyCollectionChangedEventArgs. It has 11 (in words eleven) overloaded versions of the constructor. The first argument of all constructors are an enumeration that stated the change "action" NotifyCollectionChangedAction. That is the easy part, but what to do with the remaining parameters?

It is all documented in the MSDN Library but it is in the wrong order: for each constructor it tells you which action can be used. But you need know which constructor to use for a certain action. So I create the small table below.

Reset

Add

Remove

Replace

Move

EventArgs (Action)

x

 

 

 

 

EventArgs (Action, IList changedItems)

x

x

x

 

 

EventArgs (Action, object changedItem)

x

x

x

 

 

EventArgs (Action, IList changedItems, int startingIndex)

x

x

x

 

 

EventArgs (Action, object changedItem, int index)

x

x

x

 

 

EventArgs (Action, IList newItems, IList oldItems)

 

 

 

x

 

EventArgs (Action, object newItem, object oldItem)

 

 

 

x

 

EventArgs (Action, IList newItems, IList oldItems, int startingIndex)

 

 

 

x

 

EventArgs (Action, object newItem, object oldItem, int index)

 

 

 

x

 

EventArgs (Action, IList changedItems, int index, int oldIndex)

 

 

 

 

x

EventArgs (Action, object changedItems, int index, int oldIndex)

 

 

 

 

x

And suddenly it makes sense: four versions for add & remove (single& list, indexed and not), four versions for replace, two versions for move (single & list). (Why Reset has five versions is still not clear to me ).

Hope that it is useful