简体   繁体   English

绑定到ListCollectionView(.NET 4.0)的辅助线程更新ObservableCollection

[英]Worker thread update ObservableCollection that is bound to a ListCollectionView (.NET 4.0)

I found the solution for updating observable collection from worker thread. 我找到了从工作线程更新可观察集合的解决方案。
Link to the solution But some times I get the following error: 链接到解决方案但是,有时我会收到以下错误:

“An ItemsControl is inconsistent with its items source. “ ItemsControl与它的项目来源不一致。 See the inner exception for more information.” 有关更多信息,请参见内部异常。”

Information for developers (use Text Visualizer to read this): This exception was thrown because the generator for control 'System.Windows.Controls.ListBox Items.Count:13' with name 'CAListBox' has received sequence of CollectionChanged events that do not agree with the current state of the Items collection. 供开发人员使用的信息(使用Text Visualizer读取此信息):引发此异常是因为名称为“ CAListBox”的控件“ System.Windows.Controls.ListBox Items.Count:13”的生成器收到了不同的CollectionChanged事件序列具有Items集合的当前状态。 The following differences were detected: Accumulated count 12 is different from actual count 13. [Accumulated count is (Count at last Reset + #Adds - #Removes since last Reset).] 检测到以下差异:累计计数12与实际计数13不同。[累计计数为(上次复位时的计数+#添加-#自上次复位以来的删除)。]

One or more of the following sources may have raised the wrong events: System.Windows.Controls.ItemContainerGenerator System.Windows.Controls.ItemCollection System.Windows.Data.ListCollectionView * Sample.ViewModel.ObservableCollectionEx`1[[Sample.ViewModel.Message, Sample.ViewModel, Version=1.0.1.0, Culture=neutral, PublicKeyToken=null]] 以下来源中的一个或多个可能引发了错误的事件:System.Windows.Controls.ItemContainerGenerator System.Windows.Controls.ItemCollection System.Windows.Data.ListCollectionView * Sample.ViewModel.ObservableCollectionEx`1 [[Sample.ViewModel.Message ,Sample.ViewModel,版本= 1.0.1.0,文化=中性,PublicKeyToken =空]]

I researched and found solution which will only work for .NET 4.5 and not .NET 4.0. 我研究并找到了仅适用于.NET 4.5而不适用于.NET 4.0的解决方案。 I am using .NET 4.0 visual studio 2010. Please help me out 我正在使用.NET 4.0 visual studio2010。请帮帮我

When you're updating the collection, just switch it over so it updates in the UI Thread. 当您更新集合时,只需将其切换即可在UI线程中进行更新。 You can do that by using the Dispatcher. 您可以使用Dispatcher来做到这一点。

// Other code here...

// Now update the collection in the UI Thread.  Use BeginInvoke if it needs to be Async
Application.Current.Dispatcher.Invoke(
    new Action(() => 
        {
             // Add to the collection here
             foreach (object myObject in myObjects)
             {
                 this.myCollection.Add(myObject);
             }
        }));

// Any other code needed here...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM