工作线程更新绑定到ListCollectionView(.NET 4.0)的ObservableCollection

时间:2014-03-19 22:04:57

标签: c# .net wpf xaml

我找到了从工作线程更新可观察集合的解决方案 Link to the solution 但有时我会收到以下错误:

“ItemsControl与其项目源不一致。   有关详细信息,请参阅内部异常。“

开发人员的信息(使用Text Visualizer阅读本文): 抛出此异常是因为名为“CAListBox”的控件'System.Windows.Controls.ListBox Items.Count:13'的生成器已收到与Items集合的当前状态不一致的CollectionChanged事件序列。检测到以下差异:   累计计数12与实际计数13不同。[累计计数为(上次重置时计数+ #Adds - 自上次重置后#Removes)。]

以下一个或多个来源可能引发了错误的事件:      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]]

我研究并找到了只适用于.NET 4.5而不是.NET 4.0的解决方案。 我正在使用.NET 4.0 visual studio 2010.请帮帮我

1 个答案:

答案 0 :(得分:0)

当您更新集合时,只需将其切换,以便在UI线程中更新。您可以使用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...