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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With