using System; using Xamarin.Forms; namespace MobileApp1.Views { public class ContentPageHelper { public static App GetApp(ContentPage view) => (App)GetParentElement(view); //{ // if (view == null) return null; // Element item = view.Parent; // while (true) // { // if (item == null) break; // if (item is App) break; // item = item.Parent; // } // return (item as App); //} public static Application GetApplication(ContentPage view) => (Application)GetParentElement(view); //{ // if (view == null) return null; // Element item = view.Parent; // while (true) // { // if (item == null) break; // if (item is Application) break; // item = item.Parent; // } // return (item as Application); // } public static MainPage GetMainPage(ContentPage view) => (MainPage)GetParentElement(view); public static object GetParentElement(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); //} return item; } 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); } } }