Wednesday, May 19, 2010

InvalidateRequerySuggested on GUI Thread

I've been having issues where buttons weren't getting enabled on my WPF application, only by clicking the form would they work.

I found that I need to force the refresh using CommandManager.InvalidateRequerySuggested but that didn't work, the reason being I wasn't on the GUI Thread, I was on another thread, so here is my little helper class to do it.


public static void RaiseInvalidateRequerySuggested()
{
Dispatcher dispatcher = null;

if (Application.Current != null)
{
dispatcher = Application.Current.Dispatcher;
}

if (dispatcher != null && !dispatcher.CheckAccess())
{
dispatcher.BeginInvoke(DispatcherPriority.Normal,(Action)CommandManager.InvalidateRequerySuggested);
}
}



This tries to get the application, then gets the dispatcher for the application, makes sure you have access, and then dispatches the Invalidate to that thread.

bingo.

2 comments:

  1. Anonymous21:22

    Thanks. I've been fighting with a UI the would update some of the time but not others. I didn't know how to access the main thread.

    ReplyDelete
  2. Anonymous16:25

    Thank you so much. Big help/

    ReplyDelete