RelayCommand.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Diagnostics;
  3. using System.Windows.Input;
  4. namespace VocabManager.Command
  5. {
  6. /// <summary>
  7. /// A command whose sole purpose is to
  8. /// relay its functionality to other
  9. /// objects by invoking delegates. The
  10. /// default return value for the CanExecute
  11. /// method is 'true'.
  12. /// </summary>
  13. public class RelayCommand : ICommand
  14. {
  15. #region Fields
  16. readonly Action<object> _execute;
  17. readonly Predicate<object> _canExecute;
  18. #endregion // Fields
  19. #region Constructors
  20. /// <summary>
  21. /// Creates a new command that can always execute.
  22. /// </summary>
  23. /// <param name="execute">The execution logic.</param>
  24. public RelayCommand(Action<object> execute)
  25. : this(execute, null)
  26. {
  27. }
  28. /// <summary>
  29. /// Creates a new command.
  30. /// </summary>
  31. /// <param name="execute">The execution logic.</param>
  32. /// <param name="canExecute">The execution status logic.</param>
  33. public RelayCommand(Action<object> execute, Predicate<object> canExecute)
  34. {
  35. if (execute == null)
  36. throw new ArgumentNullException("execute");
  37. _execute = execute;
  38. _canExecute = canExecute;
  39. }
  40. #endregion // Constructors
  41. #region ICommand Members
  42. [DebuggerStepThrough]
  43. public bool CanExecute(object parameter)
  44. {
  45. return _canExecute == null ? true : _canExecute(parameter);
  46. }
  47. public event EventHandler CanExecuteChanged;
  48. //{
  49. // add { CommandManager.RequerySuggested += value; }
  50. // remove { CommandManager.RequerySuggested -= value; }
  51. //}
  52. public void Execute(object parameter)
  53. {
  54. _execute(parameter);
  55. }
  56. public void RaiseCanExecuteChanged()
  57. {
  58. OnCanExecuteChanged(new EventArgs());
  59. }
  60. private void OnCanExecuteChanged(EventArgs args)
  61. {
  62. if (CanExecuteChanged != null)
  63. CanExecuteChanged(this,args);
  64. }
  65. #endregion // ICommand Members
  66. }
  67. }