我有一个位于数据模板中的 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)...
...这很奇怪。有什么想法可以解决这个问题吗?