MobileView.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using Syncfusion.XForms.PopupLayout;
  3. using Xamarin.Forms;
  4. namespace InABox.Mobile
  5. {
  6. public abstract class MobileView<TViewModel> : BaseMobileView
  7. where TViewModel : class, IMobileViewModel
  8. {
  9. private static readonly BindableProperty ViewModelProperty =
  10. BindableProperty.Create(
  11. nameof(ViewModel),
  12. typeof(TViewModel),
  13. typeof(MobileView<TViewModel>),
  14. null
  15. );
  16. public TViewModel ViewModel
  17. {
  18. get => (TViewModel)GetValue(ViewModelProperty);
  19. set
  20. {
  21. if (ViewModel != null)
  22. ViewModel.Loaded -= ViewModel_OnLoaded;
  23. SetValue(ViewModelProperty,value);
  24. if (ViewModel != null)
  25. ViewModel.Loaded += ViewModel_OnLoaded;
  26. }
  27. }
  28. private bool _loaded = false;
  29. protected override void DoBindingContextChanged()
  30. {
  31. ViewModel = BindingContext as TViewModel;
  32. Refresh();
  33. _loaded = ViewModel != null;
  34. }
  35. public void RefreshBindings()
  36. {
  37. var model = ViewModel;
  38. BindingContext = null;
  39. BindingContext = model;
  40. }
  41. private void ViewModel_OnLoaded(object sender, MobileViewModelLoadedEventArgs args)
  42. {
  43. Refresh();
  44. }
  45. public abstract void Refresh();
  46. public event MobileViewChangedEvent Changed;
  47. protected void DoChanged(string property)
  48. {
  49. if (_loaded)
  50. Changed?.Invoke(this, new MobileViewChangedEventArgs(property));
  51. }
  52. private readonly SfPopupLayout _popup = new SfPopupLayout();
  53. protected void ShowPopup(Func<View> view, int height = -1, int width = -1, int padding = 10)
  54. {
  55. _popup.PopupView.HeightRequest = height == -1 ? Application.Current.MainPage.Height * 0.8 : height;
  56. _popup.PopupView.WidthRequest = width == -1 ? Application.Current.MainPage.Width * 0.8 : width;
  57. _popup.PopupView.ShowHeader = false;
  58. _popup.PopupView.ShowFooter = false;
  59. _popup.PopupView.ContentTemplate = new DataTemplate(() =>
  60. {
  61. Grid grid = new Grid() { Margin = padding, Padding = padding};
  62. grid.Children.Add(view());
  63. return grid;
  64. });
  65. _popup.Show();
  66. }
  67. protected void DismissPopup()
  68. {
  69. _popup.Dismiss();
  70. }
  71. }
  72. }