RelayCommand.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Windows.Input;
  3. namespace UpdateDataTool
  4. {
  5. public class RelayCommand : ICommand
  6. {
  7. private readonly Action<object> _executeAction;
  8. private readonly Func<object, bool> _canExecute;
  9. /// <summary>
  10. /// Occurs when changes occur that affect whether or not the command should execute.
  11. /// </summary>
  12. public event EventHandler CanExecuteChanged;
  13. /// <summary>
  14. /// Initializes a new instance of the <see cref="RelayCommand"/> class.
  15. /// </summary>
  16. /// <param name="execute">
  17. /// The action that will be executed.
  18. /// </param>
  19. /// <param name="canExecute">The function that indicates whether the command can be executed.</param>
  20. public RelayCommand(Action execute, Func<bool> canExecute = null)
  21. : this(p => execute(), canExecute == null ? (Func<object, bool>)null : p => canExecute())
  22. {
  23. }
  24. public RelayCommand(Action<object> executeAction, Func<object, bool> canExecute = null)
  25. {
  26. _executeAction = executeAction;
  27. _canExecute = canExecute;
  28. }
  29. public void Execute(object parameter)
  30. {
  31. if (CanExecute(parameter))
  32. {
  33. _executeAction(parameter);
  34. }
  35. }
  36. public bool CanExecute(object parameter)
  37. {
  38. return _canExecute == null || _canExecute(parameter);
  39. }
  40. }
  41. }