demo-xf-app-1a/MobileApp1/Helpers/ContentViewHelper.cs

75 lines
1.9 KiB
C#
Raw Normal View History

2021-07-13 13:57:44 +00:00
using System;
using Xamarin.Forms;
namespace MobileApp1.Views
{
public class ContentViewHelper
{
2021-08-03 16:43:16 +00:00
public static App GetApp(ContentView view) => GetParentElement<App>(view);
2021-07-13 13:57:44 +00:00
2021-08-03 16:43:16 +00:00
public static Application GetApplication(ContentView view) => GetParentElement<Application>(view);
2021-07-13 13:57:44 +00:00
2021-08-03 16:43:16 +00:00
public static ContentPage GetContentPage(ContentView view) => GetParentElement<ContentPage>(view);
2021-07-13 13:57:44 +00:00
2021-08-03 16:43:16 +00:00
public static T GetParentElement<T>(ContentView view)
2021-07-13 13:57:44 +00:00
{
if (view == null) return default(T);
Element item = view.Parent;
while (true)
{
if (item == null) break;
if (item is T) break;
item = item.Parent;
}
try
{
return (T)Convert.ChangeType(item, typeof(T));
}
catch (InvalidCastException)
{
return default(T);
}
}
public static void SetMainPage(ContentView view, Page page)
{
if (view == null) return;
if (view.Parent == null) return;
if (page == null) return;
Application rs = GetApplication(view);
if (rs == null)
{
return;
}
Device.BeginInvokeOnMainThread(() =>
{
//rs.MainPage = new NavigationPage(new PasswordResetPage());
rs.MainPage = page;
});
}
public static async void PushMainPageNavigation(ContentView view, Page page)
{
if (view == null) return;
if (view.Parent == null) return;
if (page == null) return;
Application rs = GetApplication(view);
if (rs == null)
{
return;
}
await rs?.MainPage.Navigation.PushAsync(page);
}
}
}