MobileView.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using Syncfusion.XForms.PopupLayout;
  3. using Xamarin.CommunityToolkit.Extensions;
  4. using Xamarin.Forms;
  5. namespace InABox.Mobile
  6. {
  7. public abstract class MobileView<TViewModel> : BaseMobileView
  8. where TViewModel : class, IMobileViewModel
  9. {
  10. private static readonly BindableProperty ViewModelProperty =
  11. BindableProperty.Create(
  12. nameof(ViewModel),
  13. typeof(TViewModel),
  14. typeof(MobileView<TViewModel>),
  15. null
  16. );
  17. public TViewModel ViewModel
  18. {
  19. get => (TViewModel)GetValue(ViewModelProperty);
  20. set
  21. {
  22. if (ViewModel != null)
  23. ViewModel.Loaded -= ViewModel_OnLoaded;
  24. SetValue(ViewModelProperty,value);
  25. if (ViewModel != null)
  26. ViewModel.Loaded += ViewModel_OnLoaded;
  27. }
  28. }
  29. private bool _loaded = false;
  30. protected override void DoBindingContextChanged()
  31. {
  32. ViewModel = BindingContext as TViewModel;
  33. Refresh();
  34. _loaded = ViewModel != null;
  35. }
  36. public void RefreshBindings()
  37. {
  38. var model = ViewModel;
  39. BindingContext = null;
  40. BindingContext = model;
  41. }
  42. private void ViewModel_OnLoaded(object sender, MobileViewModelLoadedEventArgs args)
  43. {
  44. Refresh();
  45. }
  46. public abstract void Refresh();
  47. public event MobileViewChangedEvent Changed;
  48. protected void DoChanged(string property)
  49. {
  50. if (_loaded)
  51. Changed?.Invoke(this, new MobileViewChangedEventArgs(property));
  52. }
  53. protected void ShowPopup(Func<View> view, PopupManagerConfiguration config = null)
  54. => PopupManager.ShowPopup(this, view, config);
  55. protected void DismissPopup()
  56. => PopupManager.DismissPopup();
  57. }
  58. }