title: Adding stackpanels to a stackpanel from another thread (with dispatch?)
body: <p>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)</p>
  
  <pre><code>stackPanel1.Dispatcher.Invoke(new Action(() =&gt; stackPanel1.Children.Add(stackrow)));
  </code></pre>
  
  <p>its similar to this question:
  <a href="https://stackoverflow.com/questions/4191325/wpf-c-sharp-editing-a-listbox-from-another-thread">WPF C# - Editing a listbox from another thread</a></p>
  
  <p>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.</p>
  
  <p>How do I dispatch "stackrow" in this line? </p>
  
  <p>edit:
  stackrow is created in the foreachloop</p>
  
  <p>mainthread (creates new thread)
       Thread t = new Thread(()=> addstackrows());
       t.SetApartmentState(ApartmentState.STA);
       t.Start();</p>
  
  <p>method addstackrows()</p>
  
  <pre><code>private void addstackrows()
  {
  
    Dispatcher stackpaneldispatcher = stackPanel1.Dispatcher;                 
    stackPanel1.Dispatcher.Invoke(new Action(() =&gt; 
    stackPanel1.Children.Clear()));
    stackPanel1.Dispatcher.Invoke(new Action(() =&gt; 
    stackPanel1.Orientation = Orientation.Vertical));
  
    foreach (var randomelement in elementcollection)
    {
        StackPanel stackrow = new StackPanel();
        Dispatcher stackrowdp = stackrow.Dispatcher;
  
        stackrow.Dispatcher.Invoke(new Action(() =&gt; 
        stackrow.Orientation = Orientation.Horizontal));
        stackPanel1.Dispatcher.Invoke(new Action(() =&gt;   
        stackPanel1.Children.Add(stackrow)));
  
    }
  
  }
  </code></pre>