MobilePageStack.xaml.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Collections.Specialized;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using JetBrains.Annotations;
  9. using Xamarin.Forms;
  10. using Xamarin.Forms.Xaml;
  11. namespace InABox.Mobile
  12. {
  13. [XamlCompilation(XamlCompilationOptions.Compile)]
  14. public partial class MobilePageStack
  15. {
  16. public IList<MobilePageStackItem> Items { get; private set; }
  17. public static readonly BindableProperty SelectedIndexProperty = BindableProperty.Create(
  18. nameof(SelectedIndex),
  19. typeof(int),
  20. typeof(MobilePageStack),
  21. -1,
  22. propertyChanged:SelectedIndexChanged);
  23. private static void SelectedIndexChanged(BindableObject bindable, object oldvalue, object newvalue)
  24. {
  25. (bindable as MobilePageStack)?.SelectPage((int)newvalue);
  26. }
  27. public void SelectPage(int page)
  28. {
  29. SelectPage((page > -1) && (page < Items.Count) ? Items[page] : null);
  30. }
  31. private MobilePageStackItem _current = null;
  32. public void SelectPage([CanBeNull] MobilePageStackItem page)
  33. {
  34. if (_current != null)
  35. _current.DoDisappearing();
  36. _current = page;
  37. Content = _current?.Content;
  38. _current?.DoAppearing();
  39. SelectionChanged?.Invoke(this, EventArgs.Empty);
  40. }
  41. public int SelectedIndex
  42. {
  43. get => (int)GetValue(SelectedIndexProperty);
  44. set => SetValue(SelectedIndexProperty, value);
  45. }
  46. public static readonly BindableProperty SelectedItemProperty = BindableProperty.Create(
  47. nameof(SelectedItem),
  48. typeof(MobilePageStackItem),
  49. typeof(MobilePageStack),
  50. propertyChanged:SelectedItemChanged);
  51. private static void SelectedItemChanged(BindableObject bindable, object oldvalue, object newvalue)
  52. {
  53. (bindable as MobilePageStack)?.SelectPage(newvalue as MobilePageStackItem);
  54. }
  55. public MobilePageStackItem SelectedItem
  56. {
  57. get => GetValue(SelectedItemProperty) as MobilePageStackItem;
  58. set => SetValue(SelectedItemProperty, value);
  59. }
  60. public event EventHandler SelectionChanged;
  61. public void DoSelectionChanged()
  62. {
  63. SelectionChanged?.Invoke(this, EventArgs.Empty);
  64. }
  65. public MobilePageStack()
  66. {
  67. var items = new ObservableCollection<MobilePageStackItem>();
  68. items.CollectionChanged += ItemsChanged;
  69. Items = items;
  70. InitializeComponent();
  71. }
  72. private void ItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
  73. {
  74. Device.BeginInvokeOnMainThread(() =>
  75. {
  76. SelectedItem ??= Items.FirstOrDefault();
  77. });
  78. }
  79. }
  80. }