Adding Requery support to DelegateCommand... or another command

Topics: Prism v2 - WPF 3.5
Jan 21, 2009 at 2:05 AM
Can I ask what the reason was for not including Requery support in the DelegateCommand or if there is a plan to add a lightweight ICommand that supports Requery?
Jan 21, 2009 at 1:08 PM
Edited Jan 21, 2009 at 1:13 PM
Hi.
The DelegateCommand contains a method called RaiseCanExecuteChanged(). Nevertheless this method won't be fired automatically whenever you press any key or make any gesture with the mouse, as standard WPF RoutedCommands do.

The reason for this, is that we created the DelegateCommand as a means to decouple a the command a little more from the UI, and couple it more to the underlying ViewModel (or Presentation Model or any flavor of Presenter you like) that will handle the execution.
So you usually bind to an instance of a DelegateCommand that is hanging from a model, and the model is the one that decides whether the command's CanExecuteChanged event should be raised according to changes to that model (or to the parameter being passed), but not against any change in any part of the UI.

If for a reason you need to create a DelegateCommand because RoutedCommand does not suits your needs, but you need this particular UI requery behavior, you can do the following:

CommandManager .RequerySuggested += (s, e) => myCommand.RaiseCanExecuteChanged();

You can even inherit from DelegateCommand and add that directly to you custom DelegateCommand class if you are using this throughout your application.

I hope this helps,
Julian Dominguez
http://blogs.southworks.net/jdominguez

Jan 21, 2009 at 1:19 PM
Definitely helps Julian, thanks.

As you've said the Command is often hanging off the Model, so the logic for the CanExecute Function/Predictate is still contained in the Model (likely).  You aren't moving the ownership of the logic for validity of the Model state for that command.
Feb 22, 2010 at 7:16 AM

I think the solution suggested by Julian has a big problem: RequerySuggested is a weak event, and if you don't reference you lambda (or delegate) in other ways, it'll be collected and it won't work any more.

Bye,

Gabriele