I have a WPF application using the MVVM pattern that sometimes have to show a waitcursor when it is busy doing something the user has to wait for. Thanks to a combination of
Isak's answer did not work for me, because it did not solve the problem of how to act when the actual wait is over for the user. I ended up doing this: Everytime I start doing something timeconsuming, I call a helper-method. This helper method changes the cursor and then creates a DispatcherTimer that will be called when the application is idle. When it is called it sets the mousecursor back:
///
/// Contains helper methods for UI, so far just one for showing a waitcursor
///
public static class UiServices
{
///
/// A value indicating whether the UI is currently busy
///
private static bool IsBusy;
///
/// Sets the busystate as busy.
///
public static void SetBusyState()
{
SetBusyState(true);
}
///
/// Sets the busystate to busy or not busy.
///
/// if set to true the application is now busy.
private static void SetBusyState(bool busy)
{
if (busy != IsBusy)
{
IsBusy = busy;
Mouse.OverrideCursor = busy ? Cursors.Wait : null;
if (IsBusy)
{
new DispatcherTimer(TimeSpan.FromSeconds(0), DispatcherPriority.ApplicationIdle, dispatcherTimer_Tick, Application.Current.Dispatcher);
}
}
}
///
/// Handles the Tick event of the dispatcherTimer control.
///
/// The source of the event.
/// The instance containing the event data.
private static void dispatcherTimer_Tick(object sender, EventArgs e)
{
var dispatcherTimer = sender as DispatcherTimer;
if (dispatcherTimer != null)
{
SetBusyState(false);
dispatcherTimer.Stop();
}
}
}