I want to cancel changes in a row when user click ✖ button.
private void CancelChangesButton_Click(object sender, RoutedEventArgs e)
{
datagrid.CancelEdit();
}
CancelEdit() works great, until... my DateConverter can't ConvertBack a string. The same behaviour occurs when property setter of a ViewModel throws an exception. I can't do anything in DataGrid. The only way is to press the ESC key when cursor is in the red cell.
I try other things:
datagrid.CancelEdit(DataGridEditingUnit.Row);
datagrid.CancelEdit(DataGridEditingUnit.Cell);
datagrid.CommitEdit();
datagrid.IsReadOnly = true;
// Add new item
Nothing happened.
So I started to dig in the .NET Framework sources and I found this:
public class DataGrid : MultiSelector
...
public bool CancelEdit(DataGridEditingUnit editingUnit)
{
return EndEdit(CancelEditCommand, CurrentCellContainer, editingUnit, true);
}
The most important thing here is CurrentCellContainer that gets the value from CurrentCell. Next, I discovered that CurrentCell is following the focus. When I click ✖ button, CurrentCell changes to cell in Action column, and when I click outside DataGrid, CurrentCell changes to null.
So, I have to change CurrentCell to cell with validation error, and than invoke CancelEdit(). Do I think right?
How to find all cells with a validation error?
Is there another way to cancel editing?