Search code examples
wpfmvvminotifycollectionchanged

Can I rollback collection changes on collection changed event?


I have 2 list views...and add/remove buttons between them.

On collection changed event of a list-view-collection in viewmodel, can i rollback the changes for a particular condition ?


Solution

  • You could handle the CollectionChanged event of the ObservableCollection to backup (via the VM or whatever) the old values (see NotifyCollectionChangedEventArgs.OldItems property) and get them back when needed i.e. when user clicks 'Undo' etc.

    Update In reference to comments bellow:

    If you do want to rollback the collection from withing the CollectionChanged event-handler, create a flag where you escape the handler from a recursive call (not tested with multi-threaded application), here is a simple example, you can easily tweak it to fit in your V/VM.

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
      var x = new ObservableCollection<string>();
      x.CollectionChanged += 
        new NotifyCollectionChangedEventHandler(x_CollectionChanged);
      x.Add("asdf");
      x.Remove("asdf");
    }
    
    bool rollingBack = false;
    void x_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
      if (rollingBack) return;
    
      if (e.Action == NotifyCollectionChangedAction.Remove)
      {
        if (e.OldItems.Contains("asdf"))
        {
          var oc = (ObservableCollection<string>)sender;
          rollingBack = true;
          oc.Add("asdf");
          rollingBack = false;
        }
      }
    }