7

I have a DataGrid displaying several rows and columns of data, each is bound to its own Property. The DataGrid is NOT on a TabControl but whenever the window that it lives on is closed and reopened I get the error message: 'DeferRefresh' is not allowed during an AddNew or EditItem transaction. ONLY IF there were validations issues with one or more of the DataGrid's cells.

For example: The property bound to the DataGrid's cell is a double and the user enters "hello", of course then WPF's automatic red border is displayed around the cell. Now, if the user were to close the window, and reopen it the error would occur.

I know why the error is being thrown, because the cell is not leaving "edit mode".

How can I resolve this error?

Other Notes:

  • I have looked at this question but that is pertaining to a DataGrid on a TabControl (which mine is not).
  • I have attempted to limit the user's input so that if the Cell requires a double or then only accept a double, but the problem is there are no good ways to limit the number of decimal points (".") that the user can insert. I am controlling user input through PreviewTextInput and only allowing 0-9 and ".".

Exception Detail (if this helps)

System.InvalidOperationException was unhandled
  Message='DeferRefresh' is not allowed during an AddNew or EditItem transaction.
  Source=PresentationFramework
  StackTrace:
       at System.Windows.Data.CollectionView.DeferRefresh()
       at System.Windows.Controls.ItemCollection.SetCollectionView(CollectionView view)
       at System.Windows.Controls.ItemsControl.OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
       at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
       at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
       at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
       at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
       at System.Windows.Data.BindingExpressionBase.Invalidate(Boolean isASubPropertyChange)
       at System.Windows.Data.BindingExpression.TransferValue(Object newValue, Boolean isASubPropertyChange)
       at System.Windows.Data.BindingExpression.Activate(Object item)
       at System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)
       at System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(Boolean lastChance)
       at MS.Internal.Data.DataBindEngine.Task.Run(Boolean lastChance)
       at MS.Internal.Data.DataBindEngine.Run(Object arg)
       at MS.Internal.Data.DataBindEngine.OnLayoutUpdated(Object sender, EventArgs e)
       at System.Windows.ContextLayoutManager.fireLayoutUpdateEvent()
       at System.Windows.ContextLayoutManager.UpdateLayout()
       at System.Windows.Interop.HwndSource.SetLayoutSize()
       at System.Windows.Interop.HwndSource.set_RootVisualInternal(Visual value)
       at System.Windows.Window.SetRootVisualAndUpdateSTC()
       at System.Windows.Window.SetupInitialState(Double requestedTop, Double requestedLeft, Double requestedWidth, Double requestedHeight)
       at System.Windows.Window.CreateSourceWindow(Boolean duringShow)
       at System.Windows.Window.ShowHelper(Object booleanBox)
       at REACT.ViewModel.ReceiverListViewModel.ShowWindow(String name) in C:\Users\jcarroll42\Documents\Sandbox\REACT\SW\Source\ViewModel\ReceiverListViewModel.cs:line 238
       at REACT.Commands.ShowWindowCommand.Execute(Object parameter) in C:\Users\jcarroll42\Documents\Sandbox\REACT\SW\Source\Commands.cs:line 137
       at MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource commandSource, Boolean userInitiated)
       at System.Windows.Controls.Button.OnClick()
       at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
       at System.Windows.Input.InputManager.ProcessStagingArea()
       at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
       at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
       at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run()
       at REACT.App.Main() in C:\Users\jcarroll42\Documents\Sandbox\REACT\SW\Source\obj\x86\Debug\App.g.cs:line 0
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

I'll be happy to provide anymore information if needed.

5
  • Are you using new Window / datagrid instance every time.?
    – Liju
    Feb 22, 2013 at 17:20
  • 1
    I solved a similar problem by calling buttonBlah.Focus() inside the Window Closing event, this forces the LostFocus event to fire on the cell. Not pretty I know ... Another solution is to only allow the Window to be closed using Buttons "Save" and "Cancel".
    – Jack
    Feb 22, 2013 at 17:34
  • @JordanCarroll try handling the Window_Closing Event and clearing the datagrid data source. but as its a new grid instance every time, this issue shouldn't be happening at all.
    – Liju
    Feb 22, 2013 at 18:03
  • Well, the issue is apparently a well known bug. The problem is that the cell won't leave edit mode (if there is invalid text) because the text does not match the type of the Property. It makes sense, but it is a bug. The problem isn't that it is not losing focus either. It apparently was fixed in 4.5, but that does me no good. So far, I don't think there are any great fixes or workarounds. Feb 22, 2013 at 18:50
  • I have the same problem with .NET 4.7.1, and it got worse than it was in the beginning. Now it never cancels or commits edit mode, not only if it has validation errors. I see that LostFocus event is fired for the cell, but it seems to be to late, only the workaround mentioned by @Jack is working.
    – Anateus
    Feb 14, 2018 at 15:02

3 Answers 3

12

You can try to force datagrid into cancelling edition when you need it:

myDatagrid.CommitEdit(); 
myDatagrid.CancelEdit();

This worked for me, i had a similar issue when reordering rows.

2
  • 1
    Where do you put that code? I've tried to put it on the event raised by the button used to close the window but it does not solve the issue for me May 30, 2016 at 14:44
  • 1
    @FrancescoDS Hey i was having a similar issue, and the error was being triggered by a dataGrid.ItemsSource = data; line. I literally put it right before the line that was causing the error and it worked for me - for me it was caused by an erroneous double click on a cell in the datagrid (the double click was making the program believe the user was trying to edit the contents of a cell but that was not the intention of the users)
    – ajivani
    Jun 15, 2016 at 23:34
5

This is a bug that was fixed with .NET Framework 4.5+. Unfortunately, for those of us stuck with previous versions the error is still a problem. The best solution I have found is to simply bind the DataGrid to properties with type string. That way, full control over user input is available. With full control, the user should not be able to trigger any errors, and theDataGrid will not crash the program.

5
  • I have this exact problem with .NET 4.5.1.
    – l33t
    Jan 5, 2016 at 14:56
  • @l33t Ever fix it? I too am running .NET 4.5 and am still seeing this. Jan 27, 2016 at 21:48
  • 4
    @Jordan, can you link to the doc showing when exactly this was fixed/addressed? Was it in 4.5 or 4.5.1, 4.5.2, etc? I couldn't find anything on the searches that it was even addressed let alone fixed. Jan 27, 2016 at 21:49
  • 1
    @MarquelV, no fix yet :(
    – l33t
    Jan 27, 2016 at 22:10
  • 3
    I am facing the same problem even with .net 4.6.
    – rabejens
    Nov 27, 2016 at 12:08
1

I was having this issue .NET 4.5.1 and this was the only thing that worked for me.

    ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(MyDatagrid.ItemsSource);


                if (lcv.IsAddingNew)
                    lcv.CommitNew();
                if (lcv.IsEditingItem)
                    lcv.CommitEdit();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.