I’m trying to display a WPF Popup that will indicate some progress:
The problem is that the popup is not displayed before the Thread.Sleep completes, this is only an example, in my program I have complex IO and DB logic that needs to be executed synchronously and the progress needs to be displayed on the popup.
Here is my example code:
private ProgressBar m_ProgressBar;
private void buttonDoWork_Click(object sender, RoutedEventArgs e)
{
var progressPopup = new Popup { PopupAnimation = PopupAnimation.Fade, StaysOpen = true, Height = 150, Width = 260 };
m_ProgressBar = new ProgressBar
{
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch
};
progressPopup.Child = m_ProgressBar;
progressPopup.IsOpen = true;
Thread.Sleep(5000);
this.m_ProgressBar.Value = 25;
Thread.Sleep(5000);
this.m_ProgressBar.Value = 50;
Thread.Sleep(5000);
this.m_ProgressBar.Value = 75;
Thread.Sleep(5000);
this.m_ProgressBar.Value = 100;
}
Update
The problem is that the logic which blocks the main thread needs to stay on the main thread, there is nothing else I can do. Is there a way to run the popup on a separate thread?
Use
to update the progress bar on the UI thread.
In general you shouldn’t weave your code like this (UI and logic mixed up)
You could use the BackgroundWorker or a Task that reports progress by raising an event.
EDIT
To clarify: expose the data that changes from your ViewModel/code and raise events (PropertyChanged) so you can bind the UI to those values. That will allow you to keep UI and code separated.