DelegateCommand.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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.Controls;
  7. using System.Windows.Input;
  8. namespace FestoDebugger.Common
  9. {
  10. public interface IDelegateCommand : ICommand
  11. {
  12. void RaiseCanExecuteChanged();
  13. }
  14. public class DelegateCommand<T> : IDelegateCommand
  15. {
  16. readonly Action<T> _execute;
  17. readonly Predicate<T> _canExecute;
  18. private Action<object, SelectionChangedEventArgs> selectionAction;
  19. public event EventHandler CanExecuteChanged;
  20. public DelegateCommand(Action<T> execute)
  21. : this(execute, null)
  22. {
  23. }
  24. public DelegateCommand(Action<T> execute, Predicate<T> canExecute)
  25. {
  26. if (execute == null)
  27. throw new ArgumentNullException("execute");
  28. _execute = execute;
  29. _canExecute = canExecute;
  30. }
  31. public DelegateCommand(Action<object, SelectionChangedEventArgs> selectionAction)
  32. {
  33. this.selectionAction = selectionAction;
  34. }
  35. public bool CanExecute(object parameter)
  36. {
  37. return _canExecute == null ? true : _canExecute((T)parameter);
  38. }
  39. // The CanExecuteChanged is automatically registered by command binding, we can assume that it has some execution logic
  40. // to update the button's enabled\disabled state(though we cannot see). So raises this event will cause the button's state be updated.
  41. public void RaiseCanExecuteChanged()
  42. {
  43. if (CanExecuteChanged != null)
  44. CanExecuteChanged(this, EventArgs.Empty);
  45. }
  46. public void Execute(object parameter)
  47. {
  48. _execute((T)parameter);
  49. }
  50. }
  51. }