WPF DataGrid 未退出编辑模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15025865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:40:43  来源:igfitidea点击:

WPF DataGrid not exiting edit mode

c#wpfmvvmdatagrid

提问by Jordan Carroll

I have a DataGriddisplaying several rows and columns of data, each is bound to its own Property. The DataGridis NOT on a TabControlbut 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 IFthere were validations issues with one or more of the DataGrid's cells.

我有一个DataGrid显示多行和多列数据,每个都绑定到自己的Property. The DataGridis not on aTabControl但每当它所在的窗口关闭并重新打开时,我都会收到错误消息:'DeferRefresh' is not allowed during an AddNew or EditItem transaction.当一个或多个DataGrid的单元格存在验证问题时。

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

例如:绑定到DataGrid's的属性cell是a double,用户输入“hello”,当然然后在's'WPF's周围自动显示红色边框cell。现在,如果用户要关闭窗口,然后重新打开它,就会发生错误。

I know whythe error is being thrown, because the cellis not leaving "edit mode".

我知道为什么会抛出错误,因为cell它没有离开“编辑模式”。

How can I resolve this error?

我该如何解决这个错误?

Other Notes:

其他注意事项:

  • I have looked at this questionbut that is pertaining to a DataGridon a TabControl(which mine is not).
  • I have attempted to limit the user's input so that if the Cellrequires a doubleor 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 PreviewTextInputand only allowing 0-9 and ".".
  • 我看过这个问题,但那是关于 aDataGridTabControl(我的不是)。
  • 我试图限制用户的输入,以便如果Cell需要 adouble或者只接受 a double,但问题是没有好的方法来限制用户可以插入的小数点(“.”)的数量。我正在控制用户输入,PreviewTextInput并且只允许 0-9 和“.”。


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.

如果需要,我很乐意提供更多信息。

采纳答案by Jordan Carroll

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 DataGridto propertieswith 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 theDataGridwill not crash the program.

这是 .NET Framework 4.5+ 修复的错误。不幸的是,对于我们这些坚持使用以前版本的人来说,错误仍然是一个问题。我发现的最佳解决方案是简单地将DataGridtoproperties与 type绑定string。这样,就可以完全控制用户输入。在完全控制的情况下,用户不应触发任何错误,DataGrid也不会使程序崩溃。

回答by Natxo

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

您可以尝试在需要时强制 datagrid 取消版本:

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

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

这对我有用,我在重新排序行时遇到了类似的问题。

回答by John H

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

我在 .NET 4.5.1 上遇到了这个问题,这是唯一对我有用的方法。

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


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