ViewModelBase.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. using CommunityToolkit.Mvvm.ComponentModel;
  2. using CommunityToolkit.Mvvm.Input;
  3. using DialogHostAvalonia;
  4. using InABox.Avalonia;
  5. using InABox.Avalonia.Components;
  6. namespace PRS.DigitalKey;
  7. public abstract partial class ViewModelBase : ObservableObject, IViewModelBase
  8. {
  9. private CancellationTokenSource _cts = new();
  10. [ObservableProperty] private bool _backButtonVisible = true;
  11. [ObservableProperty] private AvaloniaMenuItemCollection _primaryMenu = new();
  12. [ObservableProperty] private AvaloniaMenuItemCollection _secondaryMenu;
  13. [ObservableProperty] private bool _reverseTransition;
  14. [RelayCommand]
  15. private void BackButtonPressed()
  16. {
  17. if (OnBackButtonPressed())
  18. Navigation.Back();
  19. }
  20. protected virtual bool OnBackButtonPressed()
  21. {
  22. return true;
  23. }
  24. public Task Activate()
  25. {
  26. var token = _cts.Token;
  27. _ = Task.Run(
  28. async () =>
  29. {
  30. var result = await Refresh();
  31. while (result != TimeSpan.Zero)
  32. {
  33. if (token.IsCancellationRequested)
  34. break;
  35. await Task.Delay(result);
  36. if (!token.IsCancellationRequested)
  37. result = await Refresh();
  38. }
  39. },
  40. token
  41. );
  42. return OnActivated();
  43. }
  44. protected virtual Task OnActivated()
  45. {
  46. return Task.CompletedTask;
  47. }
  48. private async Task<TimeSpan> Refresh()
  49. {
  50. return await OnRefresh();
  51. }
  52. protected virtual async Task<TimeSpan> OnRefresh()
  53. {
  54. return TimeSpan.FromSeconds(30);
  55. }
  56. public async Task Deactivate()
  57. {
  58. await _cts.CancelAsync();
  59. _cts.Dispose();
  60. _cts = new CancellationTokenSource();
  61. await OnDeactivated();
  62. }
  63. public bool ProgressVisible { get; set; }
  64. protected virtual Task OnDeactivated()
  65. {
  66. return Task.CompletedTask;
  67. }
  68. }
  69. public abstract class PopupViewModel : ViewModelBase, IPopupViewModel
  70. {
  71. public bool IsClosed { get; private set; }
  72. public void Close()
  73. {
  74. IsClosed = true;
  75. DialogHost.GetDialogSession(null)?.Close();
  76. }
  77. }
  78. public abstract class PopupViewModel<TResult> : PopupViewModel, IPopupViewModel<TResult>
  79. {
  80. private TResult? _result;
  81. public TResult? GetResult()
  82. {
  83. return _result ?? default;
  84. }
  85. public void Close(TResult result)
  86. {
  87. _result = result;
  88. Close();
  89. }
  90. }