In a dummy WinForms application, I can create a ListBox at design time, create a background thread at runtime, and then add controls to the ListBox from the background thread. But if I did the same in WPF, I get an error.
Why can I do this in WinForms but not in WPF? Is my WinForm example not the same as WPF? Or is there really a reason why it works great in WinForms and not in WPF?
Winforms:
private List<Label> _labels;
public Form1()
{
InitializeComponent();
Thread test = new Thread(DoStuff);
test.SetApartmentState(ApartmentState.STA);
test.Start();
}
private void DoStuff()
{
_labels = new List<Label>();
_labels.Add(new Label() { Text = "Label1" });
_labels.Add(new Label() { Text = "Label2" });
_labels.Add(new Label() { Text = "Label3" });
if (listBox1.InvokeRequired)
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.DataSource = _labels; });
}
else
{
listBox1.DataSource = _labels;
}
}
WPF:
public partial class MainWindow : Window
{
private ObservableCollection<Label> _labels;
public MainWindow()
{
InitializeComponent();
Thread test = new Thread(DoStuff);
test.SetApartmentState(ApartmentState.STA);
test.Start();
}
private void DoStuff()
{
_labels = new ObservableCollection<Label>();
_labels.Add(new Label() { Content = "Label1" });
_labels.Add(new Label() { Content = "Label2" });
_labels.Add(new Label() { Content = "Label3" });
this.Dispatcher.BeginInvoke((Action)(() =>{ icMain.ItemsSource = _labels; }));
}
}
This is the error I am getting. Pretty standard and expected:

source
share