using System; using Kent.Boogaart.HelperTrinity.Extensions; namespace Kent.Boogaart.MVVM { /// /// A command that executes delegates to determine whether the command can execute, and to execute the command. /// /// /// /// This command implementation is useful when the command simply needs to execute a method on a view model. The delegate for /// determining whether the command can execute is optional. If it is not provided, the command is considered always eligible /// to execute. /// /// public class DelegateCommand : Command { private readonly Predicate _canExecute; private readonly Action _execute; /// /// Constructs an instance of DelegateCommand. /// /// /// This constructor creates the command without a delegate for determining whether the command can execute. Therefore, the /// command will always be eligible for execution. /// /// /// The delegate to invoke when the command is executed. /// public DelegateCommand(Action execute) : this(execute, null) { } /// /// Constructs an instance of DelegateCommand. /// /// /// The delegate to invoke when the command is executed. /// /// /// The delegate to invoke to determine whether the command can execute. /// public DelegateCommand(Action execute, Predicate canExecute) { execute.AssertNotNull("execute"); _execute = execute; _canExecute = canExecute; } /// /// Determines whether this command can execute. /// /// /// If there is no delegate to determine whether the command can execute, this method will return . If a delegate was provided, this /// method will invoke that delegate. /// /// /// The command parameter. /// /// /// if the command can execute, otherwise . /// public override bool CanExecute(object parameter) { if (_canExecute == null) { return true; } return _canExecute(parameter); } /// /// Executes this command. /// /// /// This method invokes the provided delegate to execute the command. /// /// /// The command parameter. /// public override void Execute(object parameter) { _execute(parameter); } } }