【问题标题】:Worker thread update ObservableCollection that is bound to a ListCollectionView (.NET 4.0)工作线程更新绑定到 ListCollectionView (.NET 4.0) 的 ObservableCollection
【发布时间】:2014-03-19 22:04:57
【问题描述】:

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

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

给开发者的信息(使用 Text Visualizer 阅读): 引发此异常是因为名称为“CAListBox”的控件“System.Windows.Controls.ListBox Items.Count:13”的生成器已接收到与 Items 集合的当前状态不一致的 CollectionChanged 事件序列。检测到以下差异: 累计计数 12 与实际计数 13 不同。[累计计数为 (Count at last Reset + #Adds - #Removes since last Reset)。]

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

【问题讨论】:

    标签: c# .net wpf xaml


    【解决方案1】:

    当您更新集合时,只需将其切换,以便它在 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...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-28
      • 2011-01-06
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 2012-02-29
      • 2011-10-25
      • 1970-01-01
      相关资源
      最近更新 更多