MiniCommand.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Threading.Tasks;
  3. using System.Windows.Input;
  4. namespace Ryujinx.Ava.UI.Helpers
  5. {
  6. public sealed class MiniCommand<T> : MiniCommand, ICommand
  7. {
  8. private readonly Action<T> _callback;
  9. private bool _busy;
  10. private Func<T, Task> _asyncCallback;
  11. public MiniCommand(Action<T> callback)
  12. {
  13. _callback = callback;
  14. }
  15. public MiniCommand(Func<T, Task> callback)
  16. {
  17. _asyncCallback = callback;
  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. {
  34. return;
  35. }
  36. try
  37. {
  38. Busy = true;
  39. if (_callback != null)
  40. {
  41. _callback((T)parameter);
  42. }
  43. else
  44. {
  45. await _asyncCallback((T)parameter);
  46. }
  47. }
  48. finally
  49. {
  50. Busy = false;
  51. }
  52. }
  53. }
  54. public abstract class MiniCommand : ICommand
  55. {
  56. public static MiniCommand Create(Action callback) => new MiniCommand<object>(_ => callback());
  57. public static MiniCommand Create<TArg>(Action<TArg> callback) => new MiniCommand<TArg>(callback);
  58. public static MiniCommand CreateFromTask(Func<Task> callback) => new MiniCommand<object>(_ => callback());
  59. public abstract bool CanExecute(object parameter);
  60. public abstract void Execute(object parameter);
  61. public abstract event EventHandler CanExecuteChanged;
  62. }
  63. }