Can I rollback collection changes on collection changed event?

后端 未结 3 1383
你的背包
你的背包 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 04:11

    Shimmy's answer didn't work for me on a Windows Store application, you'll still run into re-entrancy issues and get an InvalidOperationException saying "Cannot change ObservableCollection during a CollectionChanged event."

    I had to use the UI's dispatcher and disable/enable the event handler to avoid these issues.

    Be warned: this is a hack, and the framework designers went to great lengths to prevent you from doings this. So if you want to ignore their warning, be careful not to shoot yourself in the foot.

    Items.CollectionChanged += ItemsChanged;
    
    private async void ItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if(condition)
        {
            //rollback
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                CoreDispatcherPriority.Normal, () => {
    
                    //disable/enable event handler
                    Items.CollectionChanged -= ItemsChanged;
    
                    Items.Remove(e.NewItems[0]);
    
                    Items.CollectionChanged += ItemsChanged;
                })).AsTask();
        }
    }
    

    This will avoid the exception, avoid calling the handler recursively, and update the UI correctly.

提交回复
热议问题