Thursday, July 30, 2009

Silverlight 3 Puzzle: Binding & DataGrid

Yesterday I had a strange bug in our application after migration to Silverlight  3.  Inner DataGrid exception was thrown when DataGrid cell with ComboBox was changed.  It took me about one day to puzzle out the bug.

I have received the following error message:

Operation is not valid due to the current state of the object.   at System.Windows.Data.BindingExpression.UpdateSource()
   at System.Windows.Controls.DataGrid.EndCellEdit(DataGridEditAction editAction, Boolean exitEditingMode, Boolean keepFocus, Boolean raiseEvents)
   at System.Windows.Controls.DataGrid.SetCurrentCellCore(Int32 columnIndex, Int32 slot, Boolean commitEdit, Boolean endRowEdit)
   at System.Windows.Controls.DataGrid.ProcessSelectionAndCurrency(Int32 columnIndex, Object item, Int32 backupSlot, DataGridSelectionAction action, Boolean scrollIntoView)
   at System.Windows.Controls.DataGrid.UpdateSelectionAndCurrency(Int32 columnIndex, Int32 slot, DataGridSelectionAction action, Boolean scrollIntoView)
   at System.Windows.Controls.DataGrid.UpdateStateOnMouseLeftButtonDown(MouseButtonEventArgs mouseButtonEventArgs, Int32 columnIndex, Int32 slot, Boolean allowEdit)
   at System.Windows.Controls.DataGridCell.DataGridCell_MouseLeftButtonDown(Object sender, MouseButtonEventArgs e)
   at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
   at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)

I have debugged my application with the sources (controls: DataGrid, DataGridColumn, DataGridTemplateColumn, DataGridCell, etc.)

This error was caused by setting binding to SelectedItem property of  ComboBox twice:

  1. In cell editing template of DataGridTemplateColumn
  2. In the body of a method overriding OnPreparingCellForEdit method of DataGrid

To resolve this problem you should remove on of binding definition.

I have reproduced this bug by creating my sample below.

bug-sh

No comments: