WPF DataGrid 'Refresh' is not allowed during an AddNew or EditItem transaction mvvm

I know its too late to answer...but for someone who is looking for answer

use cancelEdit or commitEdit method two times in a sequence like this

//for commit

this.datagrid_layers.CommitEdit();
this.datagrid_layers.CommitEdit();

//for cancel

this.datagrid_layers.CancelEdit();
this.datagrid_layers.CancelEdit();

you should be able to cast the selected item to IEditableObject and call EndEdit on it, or call the grids CancelEdit method.


There is a clean MVVM solution to the problem. First off, your ViewModels must implement IEditableObject interface (no-op should be enough). That, however, is not enough since the DataGrid will not listen to IEditableObject.CancelEdit.
Another problem is, that neither ICollectionView nor IEditableCollectionView implement the other one. While only ICollectionView can refresh, only IEditableCollectionView can commit/cancel. Luckily collection view returned by CollectionViewSource.GetDefaultView implements both:

// ViewModel.cs
public class ItemVM : IEditableObject, INotifyPropertyChanged { }

public class ModuleVM : INotifyPropertyChanged {
   ICollectionView Items { get; }

   public ModuleVM(ObservableCollection<ItemVM> items) {
      Items = CollectionViewSource.GetDefaultView(items);
   }

   public void RefreshSafely() {
      ((IEditableCollectionView)Items).CancelEdit(); // alterantively, CommitEdit()
      Items.Refresh();
   }
}

Or in other words, you can cast ICollectionView to IEditableCollectionView and call CancelEdit() first.