demo-xf-app-1a/MobileApp1/Helpers/ContentPageHelper.cs
2021-08-03 17:43:16 +01:00

108 lines
2.9 KiB
C#

using System;
using Xamarin.Forms;
namespace MobileApp1.Views
{
public class ContentPageHelper
{
public static App GetApp(ContentPage view) => GetParentElement<App>(view);
public static Application GetApplication(ContentPage view) => GetParentElement<Application>(view);
public static MainPage GetMainPage(ContentPage view) => GetParentElement<MainPage>(view);
public static T GetParentElement<T>(ContentPage view)
{
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 SetDetailPage(ContentPage view, Type pageType, bool useNavigationPage = true) => SetDetailPage(view, (Page)Activator.CreateInstance(pageType), useNavigationPage);
public static void SetDetailPage(ContentPage view, Page page, bool useNavigationPage = true)
{
if (view == null) return;
if (view.Parent == null) return;
if (page == null) return;
MainPage rs = GetMainPage(view);
if (rs == null)
{
return;
}
Device.BeginInvokeOnMainThread(() =>
{
if (useNavigationPage)
{
rs.Detail = new NavigationPage(page);
}
else
{
rs.Detail = page;
}
});
}
public static void SetMainPage(ContentPage view, Page page, bool useNavigationPage = false)
{
if (view == null) return;
if (view.Parent == null) return;
if (page == null) return;
Application rs = GetApplication(view);
if (rs == null)
{
return;
}
Device.BeginInvokeOnMainThread(() =>
{
if (useNavigationPage)
{
rs.MainPage = new NavigationPage(page);
}
else
{
rs.MainPage = page;
}
});
}
public static async void PushMainPageNavigation(ContentPage 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);
}
}
}