How to edit wpfdatagrid other cells while one of i

2020-04-11 06:54发布

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>

2条回答
一夜七次
2楼-- · 2020-04-11 07:34

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

查看更多
Bombasti
3楼-- · 2020-04-11 07:41

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;
                                       };
查看更多
登录 后发表回答