Refresh a WPF control

 
 
  • Gérald Barré

Refreshing a WPF UI element mid-execution can be tricky due to the separation between the UI thread and application logic.

Consider this classic progress bar example:

C#
int i = 0;
while (i < 100)
{
    this.myProgressBar.Value = i++;
    Thread.Sleep(500);
}

Unfortunately, the UI only updates after the method completes. A simple solution is to create an extension method that forces a render pass via the element's dispatcher:

C#
public static class ExtensionMethods
{
    private static readonly Action EmptyDelegate = delegate { };
    public static void Refresh(this UIElement uiElement)
    {
        uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
    }
}

You can then call Refresh whenever you need the control to update:

C#
int i = 0;
while (i < 100)
{
    this.myProgressBar.Value = i++;
    this.myProgressBar.Refresh();
    Thread.Sleep(500);
}

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?