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:
C#
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 of making an extension method that will implement a Refresh using the dispatcher of the element:
C#
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:
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!
Enjoy this blog?💖 Sponsor on GitHub