using System; using System.Diagnostics; using System.Windows.Input; namespace SLCommandingDemo.Commanding { /// /// A command whose sole purpose is to /// relay its functionality to other /// objects by invoking delegates. The /// default return value for the CanExecute /// method is 'true'. This class allows /// you to accept command parameters in the /// Execute and CanExecute callback methods. /// public class RelayCommand : ICommand { #region Fields readonly Action _execute = null; readonly Predicate _canExecute = null; #endregion // Fields #region Constructors public RelayCommand(Action execute) : this(execute, null) { } /// /// Creates a new command. /// /// The execution logic. /// The execution status logic. public RelayCommand(Action execute, Predicate canExecute) { if (execute == null) throw new ArgumentNullException("execute"); _execute = execute; _canExecute = canExecute; } #endregion // Constructors #region RaiseCanExecuteChanged public void RaiseCanExecuteChanged() { EventHandler handler = this.CanExecuteChanged; if (handler != null) handler(this, EventArgs.Empty); } #endregion // RaiseCanExecuteChanged #region ICommand Members [DebuggerStepThrough] public bool CanExecute(object parameter) { Debug.Assert(parameter == null || parameter is T, "Invalid parameter object type. Expected type: " + typeof(T).FullName + " Actual type: " + parameter.GetType().FullName); return _canExecute == null ? true : _canExecute((T)parameter); } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { _execute((T)parameter); } #endregion // ICommand Members } /// /// A command whose sole purpose is to /// relay its functionality to other /// objects by invoking delegates. The /// default return value for the CanExecute /// method is 'true'. This class does not allow /// you to accept command parameters in the /// Execute and CanExecute callback methods. /// public class RelayCommand : ICommand { #region Fields readonly Action _execute; readonly Func _canExecute; #endregion // Fields #region Constructors /// /// Creates a new command that can always execute. /// /// The execution logic. public RelayCommand(Action execute) : this(execute, null) { } /// /// Creates a new command. /// /// The execution logic. /// The execution status logic. public RelayCommand(Action execute, Func canExecute) { if (execute == null) throw new ArgumentNullException("execute"); _execute = execute; _canExecute = canExecute; } #endregion // Constructors #region RaiseCanExecuteChanged public void RaiseCanExecuteChanged() { EventHandler handler = this.CanExecuteChanged; if (handler != null) handler(this, EventArgs.Empty); } #endregion // RaiseCanExecuteChanged #region ICommand Members [DebuggerStepThrough] public bool CanExecute(object parameter) { return _canExecute == null ? true : _canExecute(); } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { _execute(); } #endregion // ICommand Members } }