In a dummy WinForms app, I'm able to 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 am I am able to do this in WinForms, but not WPF? Is my WinForm example not the same as the WPF one? Or is there indeed a reason why it works just fine in WinForms and not 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 receive. Pretty standard and expected: