title: Navigating to WPF window called from thread
body: <p>Yesterday I had problem with <a href="https://stackoverflow.com/questions/16080355/how-to-update-gui-in-c-sharp-wpf-from-asynchronous-method-callback">How to update gui in c# wpf from asynchronous method callback</a></p>
  
  <p>No one helped me, but I found something that worked:</p>
  
  <pre><code>System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(delegate
  {
      this.TargetWindow = new MessageListsWindow();
  }));
  th.SetApartmentState(System.Threading.ApartmentState.STA);
  th.Start();
  </code></pre>
  
  <p>Today I have a problem with changing the window, because there is an error in that operation:</p>
  
  <blockquote>
    <p>Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.</p>
  </blockquote>
  
  <p>The code works when I call it from synchronous method, but when I call it asynchronously it doesn't.</p>
  
  <p>The method to change window:</p>
  
  <pre><code>public void NavigateToWindow(CustomWindow targetWindow)
  {
      CustomWindow currentWindow = findVisualParent&lt;CustomWindow&gt;(this);
      if(currentWindow != null)
      {
          currentWindow.Close();
          //targetWindow.Dispatcher.Invoke(new Action(() =&gt; targetWindow.Show()));
          //Application.Current.Dispatcher.BeginInvoke(new Action(() =&gt; targetWindow.Show()));
          //targetWindow.Dispatcher.Invoke(new Action(() =&gt; targetWindow.Show()));
          //currentWindow.Dispatcher.Invoke(new Action(() =&gt; targetWindow.Show()));
          targetWindow.Show();
      }
  }
   private T findVisualParent&lt;T&gt;(DependencyObject child)
   where T : DependencyObject
      {
          // get parent item
          DependencyObject parentObject = VisualTreeHelper.GetParent(child);
  
          // we’ve reached the end of the tree
          if (parentObject == null) return null;
  
          // check if the parent matches the type we’re looking for
          T parent = parentObject as T;
          if (parent != null)
          {
              return parent;
          }
          else
          {
              // use recursion to proceed with next level
              return findVisualParent&lt;T&gt;(parentObject);
          }
  </code></pre>
  
  <p>Commented code is what I've tried, uncommented line works for synchronous methods. I've read that in WPF these problems are handled by dispatcher.invoke(). In window control forms I used:</p>
  
  <pre><code>this.Invoke((MethodInvoker)delegate
  {
      //changing UI
  });
  </code></pre>
  
  <p>I don't know what to do to make it work. Any help would be appreciated.</p>