using System; using System.Windows.Input; namespace VersOne.Epub.WpfDemo.Utils { /// /// A custom command which uses an action and an optional predicate supplied through one of its constructors. /// The predicate is used to determine if the command can be executed and the action is called with the command is executed. /// public class Command : ICommand { private readonly Predicate canExecute = null; private readonly Action executeAction = null; /// /// Initializes a new instance of the class with a specified execute action. /// /// An action that needs to be executed when the method is called. public Command(Action executeAction) : this(param => true, param => executeAction()) { } /// /// Initializes a new instance of the class with a specified execute action. /// /// An action that needs to be executed when the method is called. public Command(Action executeAction) : this(param => true, executeAction) { } /// /// Initializes a new instance of the class with a specified predicate that determines whether the action can be executed or not /// and a specified execute action. /// /// A predicate that is executed when the method is called. /// An action that needs to be executed when the method is called. public Command(Predicate canExecute, Action executeAction) { this.canExecute = canExecute; this.executeAction = executeAction; } /// /// Occurs after the execution of the method, so the consumer of this command can check whether the command can still be executed or not. /// public event EventHandler CanExecuteChanged; /// /// Determines whether the command can execute in its current state. /// /// /// Data used by the predicate supplied through the constructor of this command. /// If the predicate does not require data to be passed, this object can be set to null. /// /// true if this command can be executed; otherwise, false. public bool CanExecute(object parameter) { if (canExecute != null) { return canExecute(parameter); } return true; } /// /// Method called when the command is invoked. /// /// /// Data used by the action supplied through the constructor of this command. /// If the action does not require data to be passed, this object can be set to null. /// public void Execute(object parameter) { executeAction?.Invoke(parameter); UpdateCanExecuteState(); } /// /// Triggers the event. /// public void UpdateCanExecuteState() { CanExecuteChanged?.Invoke(this, new EventArgs()); } } }