I have a tab control in the GUI and there is WPF 4.0 datagrid in one of the tabs. When I click on a cell in the grid and edit something and then switch tabs, I get a Defer Refresh error:
DeferRefresh' is not allowed during an AddNew or EditItem transaction.
So I call datagrid.CancelEdit(DataGridEditingUnit.Row)
when tab is switched to cancel any pending edit and the Defer refresh issue is gone.
But what I really want to do is CommitEdit()
so that the user doesn't have to reenter the data again.
And datagrid.CommitEdit(DataGridEditingUnit.Row, true)
doesn't work for me.
I get the below error on CommitEnd()
:
Cannot perform this operation while dispatcher processing is suspended.
PS: I have tried datagrid.CommitEdit() and datagrid.CommitEdit(DataGridEditingUnit.Column, true) and it didnt work.
I solved this by adding this handler for the DataGrid's Unloaded event:
void DataGrid_Unloaded(object sender, RoutedEventArgs e)
{
var grid = (DataGrid)sender;
grid.CommitEdit(DataGridEditingUnit.Row, true);
}
I've run in to this before. WPF only keeps the current tab's view in memory; when you switch tabs, WPF unloads the current view and loads the view of the selected tab. However, DataGrid throws this exception if is currently executing a AddNew or EditItem transaction and WPF tries to unload it.
The solution for me was to keep all the tab views in memory, but only set the current tab's view to visible. This link shows a method of doing this:
WPF TabControl - Preventing Unload on Tab Change?
This change will also make your tabs load more smoothly when you switch between them because the view doesn't have to be regenerated. In my case, the extra memory usage was a reasonable trade-off.
In Xaml :
Loaded="OnUserControlLoaded"
Unloaded="OnUserControlUnloaded"
In Code Behind Inside OnUserControlLoaded
and OnUserControlUnloaded
Methods:
dataGrid.CommitEdit()
dataGrid.CancelEdit()
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