I have a ListView
that is databound to an ObservableCollection
...
<ListView x:Name="List1" ItemsSource="{Binding MyList}" />
I can't seem to find any event that are triggered when the collection changes, so I'm thinking that somehow I need to hook into the collectionchanged notification somehow? I'm not really sure how to do that.
Basically, when the collection changes I want to do additional work beyond what the ListView already does in updating it's list.
By default the
ItemsSource
is of typeIEnumerable
. You need to first cast to a type that has access to theCollectionChanged
event, then add a handler for that event.Note: I cast it to
INotifyCollectionChanged
in my example, but you can really cast it to any object that implements that. Though, as a best practice, you should cast to the most generic type that gives you access to the methods/properties/events you need. So, while you can cast it to anObservableCollection
, you don't need to.INotifyCollectionChanged
contains the event you need and if you ever decide to use some other type of collection that implements it, this will continue to work, whereas casting to anObservableCollection
means that if you one day decide that you're list is now of typeMyOwnTypeOfObservableCollectionNotDerivedFromObservableCollection
than this will break. ;)P.S. This should go in the xaml code-behind.
An ObservableCollection{T} exposes the INotifyCollectionChanged.CollectionChanged event. When binding to an ItemsSource the data binding engine handles the propogation of changes from the source to the items control, but if you need to perform additional processing you can attach a handler to the CollectionChanged event and use the NotifyCollectionChangedEventArgs it provides.
Assuming you have a public property on your view model named MyList:
you are going to have to attach the handler to your list. Or, use a
CollectionView
and hook the changed event there.in your codebehind, do like this: