RelayCommand.cs 1.9 KB

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