Search code examples
wpfvalidationxamlwpfdatagrid

How to edit wpfdatagrid other cells while one of it's cell is invalid?


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>

Solution

  • 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