Search code examples
wpfdata-bindingmvvminotifycollectionchanged

How to listen to CollectionChanged event and execute some method


My viewmodel has two Collections, one is MainCollection and other is DerivedCollection. They are displayed using a control, so that when user interacts with the mouse, items can be added or removed from MainCollection, and DerivedCollection should be refreshed accordingly.

The first part (updating MainCollection) happens automatically via data-binding, but I don' know how can I hook RefreshDerivedCollection method to MainCollection.PropertyChanged event.

Both collections and the method live in the same viewmodel.


Solution

  • You can subscribe to MainCollection.CollectionChanged and refresh derived collection there:

    MainCollection.CollectionChanged += this.OnMainCollectionChanged;
    

    and

    void OnMainCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        // TODO: Handle main collection change here.
    }