Guest User

Untitled

a guest
Nov 13th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.62 KB | None | 0 0
  1. public class NavigationService : INavigationService
  2. {
  3. readonly Dictionary<string, Type> _pagesByKey = new Dictionary<string, Type>();
  4. NavigationPage _navigation;
  5.  
  6. public string CurrentPageKey
  7. {
  8. get
  9. {
  10. lock (_pagesByKey)
  11. {
  12. if (_navigation.CurrentPage == null)
  13. {
  14. return null;
  15. }
  16.  
  17. var pageType = _navigation.CurrentPage.GetType();
  18.  
  19. return _pagesByKey.ContainsValue(pageType)
  20. ? _pagesByKey.First(p => p.Value == pageType).Key
  21. : null;
  22. }
  23. }
  24. }
  25.  
  26. public void GoBack()
  27. {
  28. Device.BeginInvokeOnMainThread(() => _navigation.PopAsync());
  29. }
  30.  
  31. public void NavigateTo(string pageKey)
  32. {
  33. NavigateTo(pageKey, null);
  34. }
  35.  
  36. public void NavigateTo(string pageKey, object parameter)
  37. {
  38. lock (_pagesByKey)
  39. {
  40. if (_pagesByKey.ContainsKey(pageKey))
  41. {
  42. var type = _pagesByKey[pageKey];
  43. ConstructorInfo constructor;
  44. object[] parameters;
  45.  
  46. if (parameter == null)
  47. {
  48. constructor = type.GetTypeInfo()
  49. .DeclaredConstructors
  50. .FirstOrDefault(c => !c.GetParameters().Any());
  51.  
  52. parameters = new object[]
  53. {
  54. };
  55. }
  56. else
  57. {
  58. constructor = type.GetTypeInfo()
  59. .DeclaredConstructors
  60. .FirstOrDefault(
  61. c =>
  62. {
  63. var p = c.GetParameters();
  64. return p.Count() == 1
  65. && p[0].ParameterType == parameter.GetType();
  66. });
  67.  
  68. parameters = new[]
  69. {
  70. parameter
  71. };
  72. }
  73.  
  74. if (constructor == null)
  75. {
  76. throw new InvalidOperationException(
  77. "No suitable constructor found for page " + pageKey);
  78. }
  79.  
  80. var page = constructor.Invoke(parameters) as Page;
  81. _navigation.PushAsync(page);
  82.  
  83. }
  84. else
  85. {
  86. throw new ArgumentException(
  87. string.Format(
  88. "No such page: {0}. Did you forget to call NavigationService.Configure?",
  89. pageKey),
  90. "pageKey");
  91. }
  92. }
  93. }
  94.  
  95. public void Configure(string pageKey, Type pageType)
  96. {
  97. lock (_pagesByKey)
  98. {
  99. if (_pagesByKey.ContainsKey(pageKey))
  100. {
  101. _pagesByKey[pageKey] = pageType;
  102. }
  103. else
  104. {
  105. _pagesByKey.Add(pageKey, pageType);
  106. }
  107. }
  108. }
  109.  
  110. public void Initialize(NavigationPage navigation)
  111. {
  112. _navigation = navigation;
  113. navigation.BarBackgroundColor = Color.FromHex("022330");
  114. navigation.BarTextColor = Color.White;
  115. }
  116. }
Add Comment
Please, Sign In to add comment