In following code (Josh Smith’s article on MVVM), can somebody give me some insight about
return _canExecute == null ? true : _canExecute(parameter); ?
it is a normal if/else statement but I’m not getting the last part of it.
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
#endregion // ICommand Members
}
Thanks.
_canExecuteis lambda function, and it can be null, depending on which constructor will instantiateRelayCommandobject. Thus, the implementation ofCanExecutemethod checks whether this function is set, and if it’s not, it returnstrue, wheras if there is function assigned, it evaluates it (given theparameter), and the evaluated value is returned as a result forCanExecute.In a nutshell:
CanExecutewill be evaluated using whatever predicate is passed along in the constructor, and in case of lack one – will always returntrue.You’ve asked that’s usually used for array/lists – it’s very similar situation. The predicate is just a function that you can pass around. When you pass such predicate to some method that is filtering a collection, the method is just calling this predicate as it would any other function.