I’m trying to bind some BindingList to ComboBox control in my WPF App. But, My BindingList is updated from other thread than the UI thread.
I made up a model. All you need is new empty project, with references to WindowsBase, PresentationCore, PresentationFramework, System.Xaml (or simply drop it into predefined WPF window).
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
public class MainWindow : Window
{
[STAThread]
public static void Main()
{
new MainWindow().ShowDialog();
}
public MainWindow()
{
BindingList<string> list = new BindingList<string>();
ComboBox cb = new ComboBox();
cb.SetBinding(ComboBox.ItemsSourceProperty, new Binding() { Source = list });
this.Content = cb;
list.Add("Goop");
new Thread(() =>
{
list.Add("Zoop");
}).Start();
}
}
In the Goop line, everything is OK. But, when it reach to the Zoop line, it thorws an exception:
This type of CollectionView does not support changes to its
SourceCollection from a thread different from the Dispatcher thread.
In the real project, I can’t move the list.Add to the UI thread, and I want to keep the Binding issue. How can it be solved? I can transit to other “List” than BindingList. I’ve tried simple List<string> but it’s worse: it doesn’t update at all when I add new items.
EDIT
In the reality, the adding-thread knows the list, but it doesn’t know the WPF window. The list is in class with internal work, and the GUI inspects the class and view it. So, the Add shouldn’t know about the GUI.
Try this ,
hope this helps