When does WPF requery commands whether they can execute? Debugger reports it happens quite often. But what is the exact set of conditions?
Asked
Active
Viewed 839 times
4
-
9I think it depends on the type of command. A `RelayCommand` usually requeries `CanExecuteChanged()` anytime any property changes (I think by running [CommandManager.InvalidateRequerySuggested](http://msdn.microsoft.com/en-us/library/system.windows.input.commandmanager.invalidaterequerysuggested.aspx) anytime a property changes), while a `DelegateCommand` does not and you have to manually have to raise the `CanExecuteChanged` when a property it relies on changes. Also, all commands are re-evaluated when they are bound, so something like hiding then showing a window will often trigger a requery – Rachel Dec 12 '12 at 16:53
-
2A little more on the topic: [How does CommandManager.RequerySuggested work?](http://stackoverflow.com/questions/2763630/how-does-commandmanager-requerysuggested-work) and [What is the actual task of CanExecuteChanged and CommandManager.RequerySuggested](http://stackoverflow.com/questions/6634777/what-is-the-actual-task-of-canexecutechanged-and-commandmanager-requerysuggested) – Blachshma Dec 12 '12 at 16:56
-
Nice topic on the subject here:http://robburke.net/2008/04/wpf-command-pattern-when-does-it-query-canexecute/ – Cornel Marian Oct 24 '13 at 17:31
-
[here is a bunch of calls to InvalidateRequerySuggested()](http://referencesource.microsoft.com/#PresentationCore/Core/CSharp/System/Windows/Input/Command/CommandManager.cs,fb01095b2fe73140) – Johan Larsson Dec 14 '14 at 23:46
-
@CornelMarian working link: https://robburke.net/wpf-command-pattern-when-does-it-query-canexecute/ – g t May 24 '19 at 10:20
1 Answers
0
The TL;DR version of it is that the CanExecute methods are called when certain inputs events occur on the Window. There are primarily Keyboard and Mouse events.
So anytime someone clicks or presses a key, ALL commands are invalidated by the CommandManager (by raising the CommandManager.RequerySuggested event). This is the reason it is important to keep CanExecute methods fast.
It is also possible to handle this yourself by creating a custom ICommand
implementation that does not use the CommandManager for the CanExecuteChanged
event.

Troels Larsen
- 4,462
- 2
- 34
- 54