2011-03-08 9 views
5

tengo este WPF DataGrid en una plantilla de datos:ArgumentOutOfRangeException en DataGridCellsPanel.BringIndexIntoView al presionar Entrar en un 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"/> 

Aquí está el controlador de eventos:

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

La clave para esto es que viewModel.EditCell provoca un evento PropertyChanged en la propiedad ValuesDataTable del modelo de vista que el DataGrid es vinculante para.

Cuando edito una celda y hago clic en ella, funciona bien. Sin embargo, cuando edito una celda y presione Enter al final de la edición, me sale esta excepción en tiempo de ejecución:

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

... lo cual es raro. ¿Alguna idea de cómo puedo evitar esto?

Respuesta

5

Tuve un problema similar al llamar al myDataGrid.ScrollIntoView(object item) directamente desde mi código. Lo arreglé llamando al myDataGrid.UpdateLayout() justo antes. Es posible que desee intentarlo si corresponde.

0

Tengo precisamente este problema y todavía no sé por qué sucede. En lugar de insatisfactorio, terminé trabajando en torno a él capturando la tecla Intro y comprometiendo manualmente la edición.

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