SubscriptionCommand.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 SubscriptionCommand<T> : ICommand
  9. {
  10. readonly Action<T> _execute;
  11. readonly Predicate<T> _canExecute;
  12. public event EventHandler CanExecuteChanged;
  13. public SubscriptionCommand(Action<T> execute)
  14. : this(execute, null)
  15. {
  16. }
  17. public SubscriptionCommand(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. }