BaseCommand.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using System;
  2. using System.Windows.Input;
  3. namespace OpenSEMI.ClientBase.Command
  4. {
  5. public class BaseCommand<T> : ICommand
  6. {
  7. private readonly Action<T> _execute = null;
  8. private readonly Predicate<T> _canExecute = null;
  9. public event EventHandler CanExecuteChanged
  10. {
  11. add
  12. {
  13. if (_canExecute != null)
  14. {
  15. CommandManager.RequerySuggested += value;
  16. }
  17. }
  18. remove
  19. {
  20. if (_canExecute != null)
  21. {
  22. CommandManager.RequerySuggested -= value;
  23. }
  24. }
  25. }
  26. public BaseCommand(Action<T> execute)
  27. : this(execute, (Predicate<T>)null)
  28. {
  29. }
  30. public BaseCommand(Action<T> execute, Predicate<T> canExecute)
  31. {
  32. if (execute == null)
  33. {
  34. throw new ArgumentNullException("execute");
  35. }
  36. _execute = execute;
  37. _canExecute = canExecute;
  38. }
  39. public bool CanExecute(object parameter)
  40. {
  41. return _canExecute == null || _canExecute((T)parameter);
  42. }
  43. public void Execute(object parameter)
  44. {
  45. _execute((T)parameter);
  46. }
  47. }
  48. public class BaseCommand : ICommand
  49. {
  50. private readonly Action _execute;
  51. private readonly Func<bool> _canExecute;
  52. public event EventHandler CanExecuteChanged
  53. {
  54. add
  55. {
  56. if (_canExecute != null)
  57. {
  58. CommandManager.RequerySuggested += value;
  59. }
  60. }
  61. remove
  62. {
  63. if (_canExecute != null)
  64. {
  65. CommandManager.RequerySuggested -= value;
  66. }
  67. }
  68. }
  69. public BaseCommand(Action execute)
  70. : this(execute, null)
  71. {
  72. }
  73. public BaseCommand(Action execute, Func<bool> canExecute)
  74. {
  75. if (execute == null)
  76. {
  77. throw new ArgumentNullException("execute");
  78. }
  79. _execute = execute;
  80. _canExecute = canExecute;
  81. }
  82. public bool CanExecute(object parameter)
  83. {
  84. return _canExecute == null || _canExecute();
  85. }
  86. public void Execute(object parameter)
  87. {
  88. _execute();
  89. }
  90. }
  91. }