I've already found several topics about multithreading in wpf and got most things to work with dispatch, but there is one thing I havent figured out yet. I have a stackpanel called "stackpanel1" to which Im adding stackpanels (in another thread) called "stackrow" as children. (foreach-loop)
stackPanel1.Dispatcher.Invoke(new Action(() => stackPanel1.Children.Add(stackrow)));
its similar to this question: WPF C# - Editing a listbox from another thread
except my "new item" is an UI Element(stackrow) and I get the following error: InvalidOperationException was unhandled. The calling thread cannot access this object because a different thread owns it.
How do I dispatch "stackrow" in this line?
edit: stackrow is created in the foreachloop
mainthread (creates new thread) Thread t = new Thread(()=> addstackrows()); t.SetApartmentState(ApartmentState.STA); t.Start();
method addstackrows()
private void addstackrows()
{
Dispatcher stackpaneldispatcher = stackPanel1.Dispatcher;
stackPanel1.Dispatcher.Invoke(new Action(() =>
stackPanel1.Children.Clear()));
stackPanel1.Dispatcher.Invoke(new Action(() =>
stackPanel1.Orientation = Orientation.Vertical));
foreach (var randomelement in elementcollection)
{
StackPanel stackrow = new StackPanel();
Dispatcher stackrowdp = stackrow.Dispatcher;
stackrow.Dispatcher.Invoke(new Action(() =>
stackrow.Orientation = Orientation.Horizontal));
stackPanel1.Dispatcher.Invoke(new Action(() =>
stackPanel1.Children.Add(stackrow)));
}
}