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
-
Toolbar, menu, and Ctrl+S never end the edit.
ToolBarandMenuare focus scopes, so focus snaps back to the cell before the command runs. AKeyBindingnever moves focus at all. Only a plain button outside the toolbar happened to work. -
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 laterICollectionView.RefreshthrowsInvalidOperationException. -
Unconvertible input blocks the commit. With
abcin anintcolumn, the commit returnsfalse. 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;
}
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)