MiniCommand.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Threading.Tasks;
  3. using System.Windows.Input;
  4. namespace MiniMvvm
  5. {
  6. public sealed class MiniCommand<T> : MiniCommand, ICommand
  7. {
  8. private readonly Action<T> _cb;
  9. private bool _busy;
  10. private Func<T, Task> _acb;
  11. public MiniCommand(Action<T> cb)
  12. {
  13. _cb = cb;
  14. }
  15. public MiniCommand(Func<T, Task> cb)
  16. {
  17. _acb = cb;
  18. }
  19. private bool Busy
  20. {
  21. get => _busy;
  22. set
  23. {
  24. _busy = value;
  25. CanExecuteChanged?.Invoke(this, EventArgs.Empty);
  26. }
  27. }
  28. public override event EventHandler CanExecuteChanged;
  29. public override bool CanExecute(object parameter) => !_busy;
  30. public override async void Execute(object parameter)
  31. {
  32. if(Busy)
  33. return;
  34. try
  35. {
  36. Busy = true;
  37. if (_cb != null)
  38. _cb((T)parameter);
  39. else
  40. await _acb((T)parameter);
  41. }
  42. finally
  43. {
  44. Busy = false;
  45. }
  46. }
  47. }
  48. public abstract class MiniCommand : ICommand
  49. {
  50. public static MiniCommand Create(Action cb) => new MiniCommand<object>(_ => cb());
  51. public static MiniCommand Create<TArg>(Action<TArg> cb) => new MiniCommand<TArg>(cb);
  52. public static MiniCommand CreateFromTask(Func<Task> cb) => new MiniCommand<object>(_ => cb());
  53. public abstract bool CanExecute(object parameter);
  54. public abstract void Execute(object parameter);
  55. public abstract event EventHandler CanExecuteChanged;
  56. }
  57. }