using System;
using System.Windows.Input;
namespace GuiWPF {
public class DelegateCommand : ICommand {
///
/// Action to be performed when this command is executed
///
private Action executionAction;
///
/// Predicate to determine if the command is valid for execution
///
private Predicate canExecutePredicate;
///
/// Initializes a new instance of the DelegateCommand class.
/// The command will always be valid for execution.
///
/// The delegate to call on execution
public DelegateCommand(Action execute)
: this(execute, null)
{
}
///
/// Initializes a new instance of the DelegateCommand class.
///
/// The delegate to call on execution
/// The predicate to determine if command is valid for execution
public DelegateCommand(Action execute, Predicate canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
this.executionAction = execute;
this.canExecutePredicate = canExecute;
}
///
/// Raised when CanExecute is changed
///
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
///
/// Executes the delegate backing this DelegateCommand
///
/// parameter to pass to predicate
/// True if command is valid for execution
public bool CanExecute(object parameter)
{
return this.canExecutePredicate == null ? true : this.canExecutePredicate(parameter);
}
///
/// Executes the delegate backing this DelegateCommand
///
/// parameter to pass to delegate
/// Thrown if CanExecute returns false
public void Execute(object parameter)
{
if (!this.CanExecute(parameter))
{
throw new InvalidOperationException("The command is not valid for execution, check the CanExecute method before attempting to execute.");
}
this.executionAction(parameter);
}
}
}