DelegateCommand.cs 1.4 KB

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