using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Input; namespace XHandler.Class { public class RelayCommand : ICommand { #region Fields /// /// Encapsulated the execute action /// private Action execute; /// /// Encapsulated the representation for the validation of the execute method /// private Predicate canExecute; #endregion // Fields #region Constructors /// /// Initializes a new instance of the RelayCommand class /// Creates a new command that can always execute. /// /// The execution logic. public RelayCommand(Action execute) : this(execute, DefaultCanExecute) { } /// /// Initializes a new instance of the RelayCommand class /// Creates a new command. /// /// The execution logic. /// The execution status logic. public RelayCommand(Action execute, Predicate canExecute) { if (execute == null) { throw new ArgumentNullException("execute"); } if (canExecute == null) { throw new ArgumentNullException("canExecute"); } this.execute = execute; this.canExecute = canExecute; } #endregion // Constructors #region ICommand Members /// /// An event to raise when the CanExecute value is changed /// /// /// Any subscription to this event will automatically subscribe to both /// the local OnCanExecuteChanged method AND /// the CommandManager RequerySuggested event /// public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; this.CanExecuteChangedInternal += value; } remove { CommandManager.RequerySuggested -= value; this.CanExecuteChangedInternal -= value; } } /// /// An event to allow the CanExecuteChanged event to be raised manually /// private event EventHandler CanExecuteChangedInternal; /// /// Defines if command can be executed /// /// the parameter that represents the validation method /// true if the command can be executed public bool CanExecute(object parameter) { return this.canExecute != null && this.canExecute(parameter); } /// /// Execute the encapsulated command /// /// the parameter that represents the execution method public void Execute(object parameter) { this.execute(parameter); } #endregion // ICommand Members /// /// Raises the can execute changed. /// public void OnCanExecuteChanged() { EventHandler handler = this.CanExecuteChangedInternal; if (handler != null) { //DispatcherHelper.BeginInvokeOnUIThread(() => handler.Invoke(this, EventArgs.Empty)); handler.Invoke(this, EventArgs.Empty); } } /// /// Destroys this instance. /// public void Destroy() { this.canExecute = _ => false; this.execute = _ => { return; }; } /// /// Defines if command can be executed (default behaviour) /// /// The parameter. /// Always true private static bool DefaultCanExecute(object parameter) { return true; } } }