在WPF Datagrid上按Enter键时,在DataGridCellsPanel.BringIndexIntoView中出现了ArgumentOutOfRangeException?

7

我有一个位于数据模板中的 WPF DataGrid

<DataGrid
    CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False"
    CanUserSortColumns="False"
    SelectionMode="Single" SelectionUnit="FullRow" GridLinesVisibility="Horizontal"
    IsEnabled="{Binding Enabled}"
    ItemsSource="{Binding ValuesDataTable}"
    CellEditEnding="DataGrid_CellEditEnding"/>

这是事件处理程序:

private void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    if (e.EditAction == DataGridEditAction.Commit)
    {
        var textBox = e.EditingElement as TextBox;
        var dataGrid = (DataGrid)sender;
        var viewModel = dataGrid.DataContext as IHasEditableCell;
        viewModel.EditCell(e.Row.GetIndex(), e.Column.DisplayIndex, textBox.Text);
        dataGrid.CancelEdit();
    }
}

关键在于viewModel.EditCell触发了视图模型的ValuesDataTable属性上的PropertyChanged事件,而这个属性是DataGrid绑定到的。
当我编辑单元格并点击它之外时,它可以正常工作。但是,当我编辑单元格并在编辑结束时按Enter键,就会出现运行时异常:
System.ArgumentOutOfRangeException was unhandled
  Message=Specified argument was out of the range of valid values.
Parameter name: index
  Source=PresentationFramework
  ParamName=index
  StackTrace:
       at System.Windows.Controls.DataGridCellsPanel.BringIndexIntoView(Int32 index)
       at System.Windows.Controls.Primitives.DataGridCellsPresenter.ScrollCellIntoView(Int32 index)
       at System.Windows.Controls.DataGrid.ScrollCellIntoView(Object item, DataGridColumn column)...

...这很奇怪。有什么想法可以解决这个问题吗?

2个回答

5

当我直接从我的代码中调用myDataGrid.ScrollIntoView(object item)时,遇到了类似的问题。我通过在此之前调用myDataGrid.UpdateLayout()来解决了这个问题。如果适用的话,您也可以尝试一下。


1
我也遇到了这个问题,但不知道为什么会出现。很遗憾,我最终只能通过捕获回车键并手动提交编辑来解决它。
    private void MyDataGrid_OnPreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {
            e.Handled = true;
            MyDataGrid.CommitEdit();
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接