DelegateCommand.cs 1.8 KB

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