In WPF datagrid
,When a cell is invalid,it prevents the the other cells editing so user can not enter data until the invalid cell comes valid.I was wonder if there is a way to disable this behavior?
There is how i use datagrid
:
<DataGrid ItemsSource="{Binding ..}">
<DataGrid.Columns>
<DataGridTextColumn Header="Name"
Binding="{Binding Name
, UpdateSourceTrigger=PropertyChanged
, NotifyOnValidationError=True
, ValidatesOnDataErrors=True
, ValidatesOnExceptions=True}"
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
If it is an mvvm application and this behavior will repeat multiple times in your application,
you can create your own DataGrid
that inherits from DataGrid
, and override the OnCellEditEnding
method like this:
public class myDataGrid : DataGrid
{
protected override void OnCellEditEnding(DataGridCellEditEndingEventArgs e)
{
e.Cancel = true;
}
}
If not, you can do the same by registrating to the CellEditEnding
event of your grid, something like this:
mainGrid.CellEditEnding += (s, e) =>
{
e.Cancel = true;
};
I overrided the OnCanExecuteBeginEdit method of the datagrid
like below and it works now.
protected override void OnCanExecuteBeginEdit(System.Windows.Input.CanExecuteRoutedEventArgs e)
{
var hasCellValidationError = false;
var hasRowValidationError = false;
const BindingFlags bindingFlags =
BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Instance;
var cellError= this.GetType().BaseType.GetProperty("HasCellValidationError", bindingFlags);
var rowError = this.GetType().BaseType.GetProperty("HasRowValidationError", bindingFlags);
if (cellError != null)
hasCellValidationError = (bool) cellErrorInfo.GetValue(this, null);
if (rowError != null)
hasRowValidationError = (bool) rowErrorInfo.GetValue(this, null);
base.OnCanExecuteBeginEdit(e);
if ((!e.CanExecute && hasCellValidationError) || (!e.CanExecute && hasRowValidationError))
{
e.CanExecute = true;
e.Handled = true;
}
}
the same question:DataGrid: On cell validation error other row cells are uneditable/Readonly