WPF DataGrid: 'DeferRefresh' is not allowed during an AddNew or EditItem transaction.

Aug 12, 2009 at 8:25 PM

To all:

I wanted to ask about this particular error message I am receiving. It is occuring on an Invalid Operation Exception - 'DeferRefresh' is not allowed during an AddNew or EditItem transaction.

To explain better: My main window contains a list of items. When the user selects an item in the list, they click an "open" button that launches a modal dialog window. This modal dialog window then displays a data grid with info relevant to the list item selected. Ok and Cancel buttons are present for persistence logic and both close the window.

The problem occurs when the window is closed before the DataGrid commits changes to a row. My persistence logic and close window logic works fine, but when I select "open" again from the main window for the same list item, I then get the InvalidOperationException with the message about DeferRefresh not allowed.

What is confusing is that it only seems to occur if one of the fields fails validation. If they all pass validation, it seems that closing the window is enough to cause end edit on the grid... but if one of them fails, like the user types in 3 caharacters for a two-letter state code (ex. CAL instead of CA), the box is outlined red as it should be, and the buttons perform properly... but next time the same item opens the bomb drops.

Any thoughts on this? Is there something I need to do in my button commands to ensure that the datagrid "ends edit" on Ok or Cancel.

The only trick to this situation is this... I am writing in MVVM. So my Ok and Cancel buttons tie to ICommands in the ViewModel, not to code-behind. This means my view model is ignorant of the grid's existence and unable to force EndEdit() in the ICommands.

Is there some other way to make a grid object end its edit from the ViewModel? Or is there a XAML setting I can change to make sure this occurs on lose focus or something?

Thank you very much ahead of time.