WPF DataGrid ItemsSource 绑定问题

发布于 2024-10-20 11:51:16 字数 3783 浏览 1 评论 0原文

我在 WPF 应用程序中有一个 DataGrid,它将自身绑定到对象的 ObservableCollection,并且一切正常。 现在,如果我在运行时修改数据网格中的单元格并删除内容,则将该单元格留空。 observableCollection 对应的值不会被修改,它将是旧值。但是,当我退出包含数据网格的窗口并重新启动窗口时,它会抛出 XamlParseException,说:“设置属性'System.Windows.Controls.ItemsControl.ItemsSource'抛出异常”

  StackTrace:
       at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
       at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
       at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
       at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
       at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
       at VO3.Start.InitializeComponent() in c:\VO\Trunk\VO3\Start.xaml:line 1
       at VO3.Start..ctor() in C:\VO\Trunk\VO3\Start.xaml.cs:line 103
  InnerException: System.InvalidOperationException
       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.ItemCollection.SetItemsSource(IEnumerable value)
            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.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
            at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
            at System.Windows.Baml2006.WpfKnownMemberInvoker.SetValue(Object instance, Object value)
            at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member, Object obj, Object value)
            at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value)
       InnerException: 

只要当我关闭了窗口,数据网格中没有单元格是空的。我还在窗口执行 InitializeComponent Line 之前检查了集合,它看起来非常好,所有对象都有正确的值,没有空或空值。我不明白为什么它会抛出这个异常。有什么想法吗? 提前致谢。

XAML:

<DataGrid HeadersVisibility="All" RowHeight="19" AutoGenerateColumns="False" Grid.Row="1" CanUserResizeColumns="False"
                              CanUserAddRows="False" CanUserDeleteRows="False" Block.TextAlignment="Right" Grid.RowSpan="2" CanUserReorderColumns="False"
                              ItemsSource="{Binding Collection}" Width="132" HorizontalAlignment="Right" Margin="10,0,10,0" CanUserSortColumns="False"
                              IsEnabled="{Binding ElementName=CheckBox, Path=SelectedIndex, Converter={StaticResource startEnabledConverter}}">

I have a DataGrid in a WPF application that binds itself to an ObservableCollection of objects, and everything works fine.
Now if I modify a cell in the datagrid during runtime, and delete the content, leave the cell empty. The observableCollection's corresponding value will not be modified, it will be the old value. But when I exit the window containing the datagrid and restart the window, it throws a XamlParseException, says:"Set Property 'System.Windows.Controls.ItemsControl.ItemsSource' threw an exception"

  StackTrace:
       at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
       at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
       at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
       at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
       at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
       at VO3.Start.InitializeComponent() in c:\VO\Trunk\VO3\Start.xaml:line 1
       at VO3.Start..ctor() in C:\VO\Trunk\VO3\Start.xaml.cs:line 103
  InnerException: System.InvalidOperationException
       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.ItemCollection.SetItemsSource(IEnumerable value)
            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.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
            at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
            at System.Windows.Baml2006.WpfKnownMemberInvoker.SetValue(Object instance, Object value)
            at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member, Object obj, Object value)
            at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value)
       InnerException: 

It won't throw the exception as long as when I closed the window, no cell in the datagrid is empty. I also checked the Collection before the Window does InitializeComponent Line and it looks perfectly fine, all the objects have the correct value, no empty or nulls. I cannot figure out why it's throwing this exception. any ideas?
Thanks in advance.

XAML:

<DataGrid HeadersVisibility="All" RowHeight="19" AutoGenerateColumns="False" Grid.Row="1" CanUserResizeColumns="False"
                              CanUserAddRows="False" CanUserDeleteRows="False" Block.TextAlignment="Right" Grid.RowSpan="2" CanUserReorderColumns="False"
                              ItemsSource="{Binding Collection}" Width="132" HorizontalAlignment="Right" Margin="10,0,10,0" CanUserSortColumns="False"
                              IsEnabled="{Binding ElementName=CheckBox, Path=SelectedIndex, Converter={StaticResource startEnabledConverter}}">

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浪菊怪哟 2024-10-27 11:51:16

DataGrid 和 DataGrid 似乎存在不少问题。延迟刷新。以下是两个相关posts

一般建议似乎是检查 DataGrid 的关联视图:一个 IEditableCollectionView (默认情况下你的,因为 ObservableCollection 在我上次查看时在绑定期间获取 ListCollectionView)并检查 IsAddingNew & IsEditingItem 以查看修改视图是否安全。此类修改将包括 DeferRefresh,它本质上是一个用于批量对视图进行修改的 Disposable。

据我所知,您遇到的问题是,当您更改 ItemsSource (这将更改或完全替换关联的绑定视图)时,DataGrid 处于事务的中间,或者视图设置为相信它是中间的。您正在清除单元格但尚未修改基础数据,这意味着它已开始编辑 (BeginEdit),但尚未提交 (CommitEdit),默认情况下,当您更改单元格时会发生这种情况。

当你关闭时就会发生这种情况重新打开窗口意味着保留了一些保留的状态,该状态仍然认为事务正在进行中。也许它仍然使用与以前相同的 ListCollectionView,并且 IsEditingItem 仍然设置为 true?

该修复很可能确保在关闭窗口之前提交所有编辑。

There appear to have been quite a few issues with the DataGrid & DeferRefresh. Here are two relevant posts:

The generic recommendation seems to be to examine the DataGrid's associated view as an IEditableCollectionView (which yours would be by default as ObservableCollection gets a ListCollectionView during binding when last I looked) and check IsAddingNew & IsEditingItem to see if it's safe to modify the view. Such modifications would include DeferRefresh, which is essentially a Disposable used to batch up modifications to the view.

As far as I can see, the problem you have is that the DataGrid is midway through a transaction, or the view is set to believe it is, whilst you are changing ItemsSource (which would change or entirely replace the associated bound view). That you are clearing out a cell but it is not yet modifying the underlying data implies it's begun an edit (BeginEdit), but not yet committed (CommitEdit), which occurs when you change cell by default.

That it is happening when you are closing & reopening the window implies that some preserved state is kept around that still thinks a transaction is in progress. Perhaps it is still using the same ListCollectionView as before, and that still has IsEditingItem set to true?

The fix is most likely to ensure that any and all edits are committed before you close the window.

百思不得你姐 2024-10-27 11:51:16

如果您要清空的字段不是字符串类型,则它可能无法正确更新。

例如,如果它是“int”并且您空白单元格,则视图模型的“int”属性将不会被设置。

我解决这个问题的方法是使用一个转换器将整数的空白值转换为零。

希望这有帮助

if the field that you are blanking out is not of type string, then it may not be updating correctly.

for example, if it is an "int" and you blank out the cell the "int" property of your viewmodel will not get set.

The way i have fixed this problem is with a converter that converts blank values for ints into zero.

hope this helps

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文