Is there a collection (BCL or other) that has the following characteristics:
Sends event if collection is changed AND sends event if any of the elements in the collection sends a PropertyChanged
event. Sort of an ObservableCollection<T>
where T: INotifyPropertyChanged
and the collection is also monitoring the elements for changes.
I could wrap an observable collection my self and do the event subscribe/unsubscribe when elements in the collection are added/removed but I was just wondering if any existing collections did this already?
Check out the C5 Generic Collection Library. All of its collections contain events that you can use to attach callbacks for when items are added, removed, inserted, cleared, or when the collection changes.
I am working for some extensions to that libary here that in the near future should allow for "preview" events that could allow you to cancel an add or change.
@soren.enemaerke: I would have made this comment on your answer post, but I can't (I don't know why, maybe because I don't have many rep points). Anyway, I just thought that I'd mention that in your code you posted I don't think that the Unsubscribe would work correctly because it is creating a new lambda inline and then trying to remove the event handler for it.
I would change the add/remove event handler lines to something like:
and
And then change the ContainedElementChanged method signature to:
This would recognise that the remove is for the same handler as the add and then remove it correctly. Hope this helps somebody :)
@soren.enemaerke Made this a reply in order to post proper code as the comments section on your answer would render it unreadable. The only issue I've had with the solution is that the particular element which triggers the
PropertyChanged
event is lost and you have no way of knowing in thePropertyChanged
call.To fix this I've created a new class
PropertyChangedEventArgsEx
and changed theContainedElementChanged
method within your class.new class
changes to your class
After this you can get the actual
Sender
element incol.PropertyChanged += (s, e)
by castinge
toPropertyChangedEventArgsEx
Again, you should note the the
s
here is the collection of elements, not the actual element that triggered the event. Hence the newSender
property in thePropertyChangedEventArgsEx
class.The simplest way to do it is just do
The BindingList class as been in .net sence 2.0. It will fire it's
ListChanged
event any time a item in the collection firesINotifyPropertyChanged
.Rxx 2.0 contains operators that along with this conversion operator for
ObservableCollection<T>
makes it easy to achieve your goal.The following property changed notification patterns are supported for
MyClass
andMyChildClass
:I would use ReactiveUI's
ReactiveCollection
: