Can I rollback collection changes on collection changed event?

后端 未结 3 1385
你的背包
你的背包 2021-02-15 03:36

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 particula

3条回答
  •  一向
    一向 (楼主)
    2021-02-15 03:50

    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();
      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)sender;
          rollingBack = true;
          oc.Add("asdf");
          rollingBack = false;
        }
      }
    }
    

提交回复
热议问题