CommandManager.InvalidateRequerySuggested()

·

,

·

1–2 minutes

In a WPF application, I have several Button controls each bound to a ICommand property of a ViewModel. In one of the method of a ViewModel, I invoke a method with a worker thread. When the method is done, it will change the value of a property, which would causes the CanExecute() method of the ICommand objects to return a different value, which would, in turn, cause the Button controls to be enabled or disabled accordingly. But nothing changes. After doing some research, I’ve found that we can call the CommandManager.InvalidateRequerySuggested() method to force the Buttons bound to ICommand object to be refreshed.

private void DoSomething()
{
    ThreadPool.QueueUserWorkItem(state =>
        {
            DoSomethingInBackgroud();
            SynchronizationContext.Current.Post(s =>
                {
                    CommandManager.InvalidateRequerySuggested();
                }, null);
       });
}

The DoSomething() method will be called when the Execute() method of the ICommand object bound to a button is called. The ThreadPool.QueueUserWorkItem() method queues the lambda code block passed in to wait its turn to be run by a worker thread. Once the DoSomethingInBackground() method is done by the worker thread, another lambda code block containing the call to the CommandManager.InvalidateRequerySuggested() method is queued to the UI thread, represented by SynchronizationContext.Current, to make sure that this method will be executed by the UI thread.

Related Articles

Get updates

Spam-free subscription, we guarantee. This is just a friendly ping when new content is out.

Go back

Your message has been sent

Warning
Warning
Warning.

2 responses to “CommandManager.InvalidateRequerySuggested()”

  1. Thanks very much for this, worked great for me with one caveat: I was getting NullReferenceExceptions when SynchronizationContext.Current was called. So to fix it I just got a reference to SynchronizationContext.Current before the call to ThreadPool.QueueUserWorkItem and used that reference instead. IE:

    var currentThread = SynchronizationContext.Current;

    ThreadPool.QueueUserWorkItem(state =>
    {
    DoSomethingInBackgroud();
    currentThread.Post(s =>
    {
    CommandManager.InvalidateRequerySuggested();
    }, null);
    });

    Then it worked great. A change in .Net Framework 4 perhaps?

    1. Thank you for the comment and sharing the code.

Leave a comment