DelegateCommand.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows.Input;
  6. namespace Aitex.Core.UI.MVVM
  7. {
  8. public class DelegateCommand<T> : ICommand
  9. {
  10. readonly Action<T> _execute;
  11. readonly Predicate<T> _canExecute;
  12. public event EventHandler CanExecuteChanged;
  13. public DelegateCommand(Action<T> execute)
  14. : this(execute, null)
  15. {
  16. }
  17. public DelegateCommand(Action<T> execute, Predicate<T> canExecute)
  18. {
  19. if (execute == null)
  20. throw new ArgumentNullException("execute");
  21. _execute = execute;
  22. _canExecute = canExecute;
  23. }
  24. public bool CanExecute(object parameter)
  25. {
  26. return _canExecute == null ? true : _canExecute((T)parameter);
  27. }
  28. // The CanExecuteChanged is automatically registered by command binding, we can assume that it has some execution logic
  29. // to update the button's enabled\disabled state(though we cannot see). So raises this event will cause the button's state be updated.
  30. public void RaiseCanExecuteChanged()
  31. {
  32. if (CanExecuteChanged != null)
  33. CanExecuteChanged(this, EventArgs.Empty);
  34. }
  35. public void Execute(object parameter)
  36. {
  37. _execute((T)parameter);
  38. }
  39. }
  40. public class DelegateCommand : ICommand
  41. {
  42. private readonly Action _execute;
  43. private readonly Func<bool> _canExecute;
  44. public DelegateCommand(Action execute) : this(execute, null) { }
  45. public DelegateCommand(Action execute, Func<bool> canExecute)
  46. {
  47. _execute = execute ?? throw new ArgumentNullException(nameof(execute));
  48. _canExecute = canExecute;
  49. }
  50. public void Execute(object parameter)
  51. {
  52. _execute();
  53. }
  54. public bool CanExecute(object parameter)
  55. {
  56. if (_canExecute == null) return true;
  57. return _canExecute();
  58. }
  59. public event EventHandler CanExecuteChanged
  60. {
  61. add => CommandManager.RequerySuggested += value;
  62. remove => CommandManager.RequerySuggested -= value;
  63. }
  64. }
  65. }