ItemsControl与其项目源 – WPF Listbox不一致

我有一个WPF窗口,其中包含一个ListBox控件,该控件在执行按钮单击方法时填充。

XAML:

                   

C#:

  private void CheckforThirdPartyUpdatesButton_Click(object sender, RoutedEventArgs e) { CheckforThirdPartyUpdatesButton.IsEnabled = false; worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; worker.DoWork += delegate(object s, DoWorkEventArgs args) { MainEntry.checkFor3PUpdates(); }; worker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args) { }; worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args) { ThirdPartyListBox.DataContext = RegScan_ThirdParty.comparisonListWithState; CheckforThirdPartyUpdatesButton.IsEnabled = true; }; worker.RunWorkerAsync(); } 

到目前为止,所有内容都按预期运行,并且列表框中填充了多行项目,具体取决于列表中的项目数量ThirdPartyListBox.DataContext = RegScan_ThirdParty.comparisonListWithState; 。 但是,如果我与列表框项目进行交互,则会抛出InvalidOperationException,内部exception“一个ItemsControl与其项目源不一致”。

有人可以帮我理解发生了什么吗?

当项目的源从另一个线程发生更改并且ListBox没有收到有关正在更改的ItemsSource的通知( CollectionChanged事件)时,抛出此类exception; 所以当它开始做一些工作(比如更新布局)时,它会看到Items不等于ItemsSource并抛出exception。

从.NET 4.5开始,WPF提供了一种与从不同线程更改的集合启用同步的方法。 尝试在ItemsSource上使用EnableCollectionSynchronization方法。

您可以在控件上简单地调用Refresh()方法,其中绑定资源已更改:

 myListBox.Items.Refresh();