RelayCommand.cs (2970B)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Windows.Input; 7 8 namespace File360.Common 9 { 10 /// <summary> 11 /// A command whose sole purpose is to relay its functionality 12 /// to other objects by invoking delegates. 13 /// The default return value for the CanExecute method is 'true'. 14 /// <see cref="RaiseCanExecuteChanged"/> needs to be called whenever 15 /// <see cref="CanExecute"/> is expected to return a different value. 16 /// </summary> 17 public class RelayCommand : ICommand 18 { 19 private readonly Action _execute; 20 private readonly Func<bool> _canExecute; 21 22 /// <summary> 23 /// Raised when RaiseCanExecuteChanged is called. 24 /// </summary> 25 public event EventHandler CanExecuteChanged; 26 27 /// <summary> 28 /// Creates a new command that can always execute. 29 /// </summary> 30 /// <param name="execute">The execution logic.</param> 31 public RelayCommand(Action execute) 32 : this(execute, null) 33 { 34 } 35 36 /// <summary> 37 /// Creates a new command. 38 /// </summary> 39 /// <param name="execute">The execution logic.</param> 40 /// <param name="canExecute">The execution status logic.</param> 41 public RelayCommand(Action execute, Func<bool> canExecute) 42 { 43 if (execute == null) 44 throw new ArgumentNullException("execute"); 45 _execute = execute; 46 _canExecute = canExecute; 47 } 48 49 /// <summary> 50 /// Determines whether this <see cref="RelayCommand"/> can execute in its current state. 51 /// </summary> 52 /// <param name="parameter"> 53 /// Data used by the command. If the command does not require data to be passed, this object can be set to null. 54 /// </param> 55 /// <returns>true if this command can be executed; otherwise, false.</returns> 56 public bool CanExecute(object parameter) 57 { 58 return _canExecute == null ? true : _canExecute(); 59 } 60 61 /// <summary> 62 /// Executes the <see cref="RelayCommand"/> on the current command target. 63 /// </summary> 64 /// <param name="parameter"> 65 /// Data used by the command. If the command does not require data to be passed, this object can be set to null. 66 /// </param> 67 public void Execute(object parameter) 68 { 69 _execute(); 70 } 71 72 /// <summary> 73 /// Method used to raise the <see cref="CanExecuteChanged"/> event 74 /// to indicate that the return value of the <see cref="CanExecute"/> 75 /// method has changed. 76 /// </summary> 77 public void RaiseCanExecuteChanged() 78 { 79 var handler = CanExecuteChanged; 80 if (handler != null) 81 { 82 handler(this, EventArgs.Empty); 83 } 84 } 85 } 86 }