Refresh a WPF control

When you want to refresh an element of the GUI in wpf it is always delicate because of the decoupling graphic/functional…

The classic case of a ProgressBar:

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

Unfortunately the refreshment is only done at the end of the method. There is one solution that consists in making an extension method that will implement a Refresh using the dispatcher of the element:

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

Then, you can call the Refresh method when you want:

int i = 0;
while (i < 100)
{
    this.myProgressBar.Value = i++;
    this.myProgressBar.Refresh();
    Thread.Sleep(500);
}
Enjoy this blog? Buy Me A Coffee Donate with PayPal

Leave a reply