tags:

views:

301

answers:

4

I am doing the following tutorial, to learn about the MVVM pattern in WPF. There's something I don't understand about the following seemingly partly given implementation of ICommand interface.

In the code below the _canExecute variable is used as a method and a variable. I was thinking it's some event of some kind, but ICommand already has an event to be implemented and it's not _canExecute.

So can someone help me as to what _canExecute is supposed to be?

 1: #region ICommand Members
  2: 
  3: public bool CanExecute(object parameter) {
  4:     return _canExecute == null ? true : _canExecute(parameter);
  5: }
  6: 
  7: public event EventHandler CanExecuteChanged {
  8:     add { CommandManager.RequerySuggested += value; }
  9:     remove { CommandManager.RequerySuggested -= value; }
 10: }
 11: 
 12: public void Execute(object parameter) {
 13:     _execute(parameter);
 14: }
 15: 
 16: #endregion
A: 

I may be wrong, but as far as I know how ICommand is usually implemented and I can understand the tutorial, there is a bug and it should read

public bool CanExecute(object parameter) {
   return _execute == null ? false : true;
}

or perhaps _canExecute is a function object to which a request is forwarded. In that case, the tutorial is unclear.

Anyway, I would consult with the author what he had in mind.

mloskot
A: 

I think writer of the code wanted to decouple CanExecute logic via Predicate delegate so inheritors of Base Command class can decide wheter or not CanExecute like this

class DefaultCommand:BaseCommand
{
    //_canExecute is supposed protected Predicate<string> in base class
    public DefaultCommand()
    {
       base._canExecute =x=>x=="SomeExecutable";
    }
}
mcaaltuntas
A: 

The default assumption is that CanExecute is always true unless a bool delegate has been passed to assess otherwise.

Antony Koch
What would be the return type of _canExecute? That's what I'm trying to figure out?
Tony
A boolean (in predicate form) - it'd have to be according to the above implementation. It'll be a delegate, e.g. bool CanExecuteMethod(object parameter) { return ((Class)parameter).somethingReturningABoolean;}
Antony Koch
+3  A: 

_canExecute would be a Predicate<object>, whereas _execute would be an Action<object>.

See my delegate command blog post for another example.

HTH,
Kent

Kent Boogaart
Kent - not a biggie, but you might want to note: http://meta.stackoverflow.com/questions/5029
Marc Gravell