WPF: How do I hook into a ListView's ItemsSource CollectionChanged notification?

15,626

By default the ItemsSource is of type IEnumerable. You need to first cast to a type that has access to the CollectionChanged event, then add a handler for that event.

((INotifyCollectionChanged)List1.ItemsSource).CollectionChanged +=
    new NotifyCollectionChangedEventHandler(List1CollectionChanged);

public void List1CollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
{
    // Your logic here
}


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 an ObservableCollection, 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 an ObservableCollection means that if you one day decide that you're list is now of type MyOwnTypeOfObservableCollectionNotDerivedFromObservableCollection than this will break. ;)

P.S. This should go in the xaml code-behind.

Share:
15,626
michael
Author by

michael

Updated on June 13, 2022

Comments

  • michael
    michael almost 2 years

    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.

  • myermian
    myermian about 13 years
    This would work if the original poster wants the logic to be on the ViewModel, but I'm going to guess that he wants additional logic on the View since he showed some XAML and binding. I could be wrong though.
  • michael
    michael about 13 years
    This worked perfectly, and thanks for the information about casting.