Feeds:
Posts
Comments

Posts Tagged ‘Thread’

CommandManager.InvalidateRequerySuggested()

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.

Read Full Post »