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?
Made a quick implementation myself:
Admitted, it would be kind of confusing and misleading to have the PropertyChanged fire on the collection when the property that actually changed is on a contained element, but it would fit my specific purpose. It could be extended with a new event that is fired instead inside ContainerElementChanged
Thoughts?
EDIT: Should note that the BCL ObservableCollection only exposes the INotifyPropertyChanged interface through an explicit implementation so you would need to provide a cast in order to attach to the event like so:
EDIT2: Added handling of ClearItems, thanks Josh
EDIT3: Added a correct unsubscribe for PropertyChanged, thanks Mark
EDIT4: Wow, this is really learn-as-you-go :). KP noted that the event was fired with the collection as sender and not with the element when the a contained element changes. He suggested declaring a PropertyChanged event on the class marked with new. This would have a few issues which I'll try to illustrate with the sample below:
You can see from the sample that 'overriding' the event has the side effect that you need to be extremely careful of which type of variable you use when subscribing to the event since that dictates which events you receive.
If you want to use something built into the framework you can use FreezableCollection. Then you will want to listen to the Changed event.
Here is a small sample. The collection_Changed method will get called twice.