Command.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Windows.Input;
  3. namespace Flyinsono.Client.Test
  4. {
  5. /// <summary>
  6. /// Implementation of ICommand
  7. /// </summary>
  8. public abstract class Command : ViewModel, ICommand
  9. {
  10. private readonly Action<object> _executeAction;
  11. private readonly Func<object, bool> _canExecuteFunc;
  12. public event EventHandler CanExecuteChanged;
  13. protected Command(Action<object> executeAction, Func<object, bool> canExecuteFunc = null)
  14. {
  15. if (executeAction == null)
  16. {
  17. throw new NullReferenceException("Execute Action can not be null");
  18. }
  19. _executeAction = executeAction;
  20. _canExecuteFunc = canExecuteFunc;
  21. }
  22. /// <summary>
  23. /// If this command can executed
  24. /// </summary>
  25. /// <param name="parameter"></param>
  26. /// <returns></returns>
  27. public bool CanExecute(object parameter)
  28. {
  29. if (!IsEnabled)
  30. {
  31. return false;
  32. }
  33. if (_canExecuteFunc != null)
  34. {
  35. return _canExecuteFunc(parameter);
  36. }
  37. return true;
  38. }
  39. /// <summary>
  40. /// Execute the command
  41. /// </summary>
  42. /// <param name="parameter"></param>
  43. public void Execute(object parameter)
  44. {
  45. if (CanExecute(parameter))
  46. {
  47. Logger.WriteLineInfo($"Execute Command with description {Description}");
  48. _executeAction(parameter);
  49. }
  50. }
  51. public virtual void OnCanExecuteChanged()
  52. {
  53. CanExecuteChanged?.Invoke(this, EventArgs.Empty);
  54. }
  55. protected override void OnIsEnabledChanged()
  56. {
  57. OnCanExecuteChanged();
  58. base.OnIsEnabledChanged();
  59. }
  60. }
  61. }