DEV Community

Cover image for Why a WPF DataGrid Edit Does Not Reach the ViewModel When Save Is Clicked, and How to Use CommitEdit
s-iguchi09
s-iguchi09

Posted on Originally published at s-iguchi09.github.io AI-assisted

Why a WPF DataGrid Edit Does Not Reach the ViewModel When Save Is Clicked, and How to Use CommitEdit

A user types into a DataGrid cell and clicks Save in the toolbar without leaving the cell. The grid still shows the new text, but the view model saves the old value. No exception, no warning.

This is a short summary. The full article, with a table of measured results for each save path on .NET 10, is here:
Why a WPF DataGrid Edit Does Not Reach the ViewModel When Save Is Clicked

Three things get in the way

  1. Toolbar, menu, and Ctrl+S never end the edit. ToolBar and Menu are focus scopes, so focus snaps back to the cell before the command runs. A KeyBinding never moves focus at all. Only a plain button outside the toolbar happened to work.
  2. CommitEdit() with no arguments is not enough. Called while a cell is being edited, it only commits the cell into the pending row. The source keeps the old value, and a later ICollectionView.Refresh throws InvalidOperationException.
  3. Unconvertible input blocks the commit. With abc in an int column, the commit returns false. Saving anyway stores stale data.

The fix

Commit the whole row at the start of the save, and stop if it fails:

bool committed = grid.CommitEdit(DataGridEditingUnit.Row, true);
if (!committed)
{
    // Tell the user about the invalid input and do not save.
    return;
}
Enter fullscreen mode Exit fullscreen mode

To keep the view model unaware of the DataGrid, the full article passes this call in from code-behind as a Func<bool>. It also explains why UpdateSourceTrigger=PropertyChanged and FocusManager.IsFocusScope="False" are not real substitutes.

A Japanese version is also available.

Top comments (0)