Command.cs 1.9 KB

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