DelegateCommand.cs 1.6 KB

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