1

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 
0

4 Answers 4

3

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

See my delegate command blog post for another example.

Sign up to request clarification or add additional context in comments.

1 Comment

Kent - not a biggie, but you might want to note: meta.stackexchange.com/questions/5029
0

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.

Comments

0

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"; } } 

Comments

0

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

2 Comments

What would be the return type of _canExecute? That's what I'm trying to figure out?
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; }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.