title: WPF : Refresh / Update control on Window load
body: <p>I want to display time in the Label. The label contents needs to be refreshed automatically as the window is loaded.</p>
  <p>I have a simple WPF Window with a Label control in it. As illustrated here</p>
  <pre><code>&lt;Window x:Class=&quot;shoes.Window1&quot;
      xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
      xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
      Title=&quot;Window1&quot; Height=&quot;300&quot; Width=&quot;300&quot; Loaded=&quot;Window_Loaded&quot;&gt;
      &lt;Grid&gt;
          &lt;Label Margin=&quot;12&quot; Name=&quot;lblSeconds&quot;&gt;&lt;/Label&gt;
          &lt;Button Margin=&quot;68,22,135,0&quot; Name=&quot;button1&quot; Height=&quot;24&quot; VerticalAlignment=&quot;Top&quot; Click=&quot;button1_Click&quot;&gt;Button&lt;/Button&gt;
      &lt;/Grid&gt;
  &lt;/Window&gt;
  </code></pre>
  <p>I have looked at the code available here : <a href="https://web.archive.org/web/20201130173223/http://geekswithblogs.net/NewThingsILearned/archive/2008/08/25/refresh--update-wpf-controls.aspx" rel="nofollow noreferrer">http://geekswithblogs.net/NewThingsILearned/archive/2008/08/25/refresh--update-wpf-controls.aspx</a></p>
  <p>And I modified to fit this way :</p>
  <pre><code>public partial class Window1 : Window
  {
      private static Action EmptyDelegate = delegate() { };
  
      public Window1()
      {
          InitializeComponent();
          
      }
  
      private void Window_Loaded(object sender, RoutedEventArgs e)
      {
          if (IsLoaded)
          {
              LoopingMethod();
          }
      }
  
      private void LoopingMethod()
      {
          while(true)
          {
              lblSeconds.Content = DateTime.Now.ToLongTimeString();
              lblSeconds.Refresh();
              Thread.Sleep(10);
          }
      }
  }
  public static class ExtensionMethods
  {
  
      private static Action EmptyDelegate = delegate() { };
  
  
      public static void Refresh(this UIElement uiElement)
      {
          uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
      }
  }
  </code></pre>
  <p>I have discovered the code works pretty well when it is triggered through a button_Click event. I have tried to get the code to run through a Window_Loaded event like this but in vain. The window content is never displayed.</p>
  <p>What I can do to get the label updated automatically when the window is loaded?</p>