Advertisement
Guest User

Untitled

a guest
Sep 11th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. public class DelegateCommand : ICommand
  2. {
  3. private readonly Action _action;
  4. private readonly Func<bool> _canExecute;
  5.  
  6. public event EventHandler CanExecuteChanged
  7. {
  8. add => CommandManager.RequerySuggested += value;
  9. remove => CommandManager.RequerySuggested -= value;
  10. }
  11.  
  12. public DelegateCommand(Action action)
  13. {
  14. _action = action ?? throw new ArgumentNullException(nameof(action));
  15. }
  16.  
  17. public DelegateCommand(Action action, Func<bool> canExecuteEvaluator) : this(action)
  18. {
  19. _canExecute = canExecuteEvaluator ?? throw new ArgumentNullException(nameof(canExecuteEvaluator));
  20. }
  21.  
  22. public bool CanExecute(object parameter)
  23. {
  24. return _canExecute?.Invoke() ?? true;
  25. }
  26.  
  27. public void Execute(object parameter)
  28. {
  29. _action();
  30. }
  31. }
  32.  
  33. public class DelegateCommand<T> : ICommand
  34. {
  35. private readonly Action<T> _action;
  36. private readonly Predicate<T> _canExecute;
  37.  
  38. public DelegateCommand(Action<T> action, Predicate<T> canExecute = null)
  39. {
  40. _action = action ?? throw new ArgumentNullException(nameof(action));
  41. _canExecute = canExecute;
  42. }
  43.  
  44. public bool CanExecute(object parameter)
  45. {
  46. return _canExecute == null || _canExecute((T)parameter);
  47. }
  48.  
  49. public event EventHandler CanExecuteChanged
  50. {
  51. add => CommandManager.RequerySuggested += value;
  52. remove => CommandManager.RequerySuggested -= value;
  53. }
  54.  
  55. public void Execute(object parameter)
  56. {
  57. _action((T)parameter);
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement