When is CanExecute called?

I try to search for "the CommandManager detects conditions" and reach this exellent article.

By examining .NET Framework source code, the author finds that the CommandManager doesn't detect conditions by itself, rather than when Keyboard.KeyUpEvent, Mouse.MouseUpEvent, Keyboard.GotKeyboardFocusEvent, or Keyboard.LostKeyboardFocusEvent occurs, it will reevaluate CanExecute method.

The article includes other information, but the above part has been enough for me.


The technical answer is that CanExecute will be invoked whenever the CommandManager.RequerySuggested event is raised. According to the documentation, this will be...

...when the CommandManager detects conditions that might change the ability of a command to execute.

In practical terms, this just means that you don't need to worry about when CanExecute is called: WPF will invoke it when it thinks it is appropriate, and in my experience this will almost always cover your requirements.

The exception to this is if you have a background task that will cause CanExecute to change it's return value based on something that is not triggered by the UI. In this scenario, you may need to manually force the WPF runtime to re-query CanExecute which you can do by calling CommandManager.InvalidateRequerySuggested

Tags:

C#

.Net

Wpf