开发者

ArgumentOutOfRangeException in DataGridCellsPanel.BringIndexIntoView when pressing enter on a WPF Datagrid?

开发者 https://www.devze.com 2023-02-16 02:05 出处:网络
I have this WPF DataGrid in a data template: <DataGrid CanUserAddRows=\"False\" CanUserDeleteRows=\"False开发者_如何转开发\" CanUserReorderColumns=\"False\"

I have this WPF DataGrid in a data template:

<DataGrid
    CanUserAddRows="False" CanUserDeleteRows="False开发者_如何转开发" CanUserReorderColumns="False"
    CanUserSortColumns="False"
    SelectionMode="Single" SelectionUnit="FullRow" GridLinesVisibility="Horizontal"
    IsEnabled="{Binding Enabled}"
    ItemsSource="{Binding ValuesDataTable}"
    CellEditEnding="DataGrid_CellEditEnding"/>

Here's the event handler:

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

The key to this is that viewModel.EditCell raises a PropertyChanged event on the ValuesDataTable property of the view model that the DataGrid is binding to.

When I edit a cell and click off of it, it works fine. However, when I edit a cell and press Enter at the end of the edit, I get this runtime exception:

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)...

... which is weird. Any ideas how I can get around this?


I had a similar problem when calling myDataGrid.ScrollIntoView(object item) directly from my code. I fixed it by calling myDataGrid.UpdateLayout() just before. You might want to give that a try if applicable.


I have precisely this problem and still don't know why it happens. Rather unsatisfactorily, I ended up working around it by catching the enter key and manually commiting the edit.

    private void MyDataGrid_OnPreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {
            e.Handled = true;
            MyDataGrid.CommitEdit();
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消