title: WPF: In an attached property, how to wait until visual tree loaded properly?
body: <p>I have an Attached Property in a WPF app.</p>
  
  <p>The code below is inside the <code>OnLoad</code> event, but it doesn't work unless I add a hacky 500 millisecond delay in.</p>
  
  <p>Is there some way to avoid this delay, and detect when the visual tree has been loaded?</p>
  
  <pre><code>private static void FrameworkElement_Loaded(object sender, RoutedEventArgs e)
  {
      // ... snip...
      Window window = GetParentWindow(dependencyObject);
  
      // Without this delay, changing properties does nothing.
      Task task = Task.Run(
          async () =&gt;
          {
              {
                  // Without this delay, changing properties does nothing.
                  await Task.Delay(TimeSpan.FromMilliseconds(500));
  
                  Application.Current.Dispatcher.Invoke(
                      () =&gt;
                      {
                          // Set False &gt;&gt; True to trigger the dependency property.
                          window.Topmost = false;
                          window.Topmost = true;                                              
                      });
              }
          });
   }
  </code></pre>
  
  <h1>Update 1</h1>
  
  <p>As per the answer from @Will, "use the dispatcher and select the appropriate priority". This works brilliantly:</p>
  
  <pre><code>private static void FrameworkElement_Loaded(object sender, RoutedEventArgs e)
  {
     // Wrap *everything* in a Dispatcher.Invoke with an appropriately
     // low priority, to defer until the visual tree has finished updating.
     Application.Current.Dispatcher.Invoke(
     async () =&gt;
          {
              // This puts us to the back of the dispatcher queue.
              await Task.Yield();
  
              // ... snip...
              Window window = GetParentWindow(dependencyObject);
  
              window.Topmost = true;                                              
          }, 
          // Use an appropriately low priority to defer until 
          // visual tree updated.
          DispatcherPriority.ApplicationIdle);
   }
  </code></pre>
  
  <h1>Update 2</h1>
  
  <p>If using DevExpress, the <a href="https://documentation.devexpress.com/#WPF/clsDevExpressMvvmUILayoutTreeHelpertopic" rel="nofollow noreferrer">LayoutTreeHelper</a> class is useful for scanning up and down the visual tree.</p>
  
  <p>For sample code that deals with scanning up and down the visual tree, see:</p>
  
  <ul>
  <li><a href="https://www.devexpress.com/support/center/Question/Details/T357763#comment-c6213e79-bf9a-48f0-b972-899275fbff31" rel="nofollow noreferrer">DevExpress: In an attached property, how to wait until we are 100% sure that DevExpress has finished building its Visual Tree?</a></li>
  <li><a href="https://www.devexpress.com/Support/Center/Question/Details/T355336" rel="nofollow noreferrer">DevExpress and How to ensure that a LayoutPanel is always in front of everything else?</a></li>
  </ul>
  
  <h1>Update 3</h1>
  
  <p>If you are in an attached property, the only way to reliably load the visual tree is to execute the code in or after the <code>Loaded</code> event handler. If we are not aware of this limitation, then everything will fail intermittently. Waiting until after the <code>OnLoaded</code> event has fired is far superior to any other method that attempts to introduce other random forms of delays, as noted above.</p>
  
  <p>If you are using DevExpress, this is even more critical: attempting to do anything before the <code>Loaded</code> event can, in some circumstances, result in a crash. </p>
  
  <p>For example:</p>
  
  <ul>
  <li>Calling <code>window.Show()</code> before the <code>Loaded</code> event has resulted in a crash in some circumstances.</li>
  <li>Hooking into the event handler for <code>IsVisibleChanged</code> before the <code>Loaded</code> event has result in a crash in some circumstances.</li>
  </ul>
  
  <hr>
  
  <p><em>Disclaimer: I am not associated with DevExpress, it one of many good WPF libraries, I also recommend Infragistics.</em></p>