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

∥☆過路亽.° 提交于 2019-12-04 04:27:28

问题


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>

回答1:


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;
                                       };



回答2:


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



来源:https://stackoverflow.com/questions/18810009/how-to-edit-wpfdatagrid-other-cells-while-one-of-its-cell-is-invalid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!