So basically I'm try to to find out if a page was pushed modally.
Here is the code I have for my extension method:
public static bool IsModal(this Page page)
{
return page.Navigation.ModalStack.Any(p => page == p);
}
The issue is; p
never equals page
due to the fact p
changes to NavigationPage during runtime although intellisense reports it as a type of Page at compile time.
I've tried casting p
to a Page but the type does not change at runtime and intellisense just moans that the cast is redundant.
I call this extension by using CurrentPage.IsModal
in my View Model. CurrentPage
is a type of Page at compile time but then changes to NavigationPage at runtime.
The confusing thing is that during debugging, p
has properties such as CurrentPage
and RootPage
which show in the debugger, but these are not accessible by using p.CurrentPage
as the compiler complains they don't exist !?! I was going to try an compare these but I can't access them but can view them in the debugger.
You need to check the type of page first, a page without navigationbar can also be pushed modally:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void Button_Clicked(object sender, EventArgs e)
{
Page1 p = new Page1();
await this.Navigation.PushModalAsync(p, true);
bool b = PageExtensions.IsModal(p);
Console.WriteLine(b);
}
}
public static class PageExtensions
{
public static bool IsModal(this Page page)
{
if (page.GetType() == typeof(NavigationPage))
{
return page.Navigation.ModalStack.Any(p => ((NavigationPage)p).CurrentPage.Equals(page));
}
else
{
return page.Navigation.ModalStack.Any(p => p.Equals(page));
}
}
}
So this code works:
public static class PageExtensions
{
public static bool IsModal(this Page page)
{
return page.Navigation.ModalStack.Any(p=> ((NavigationPage) p).CurrentPage.Equals(page));
}
}
I'm concerned that is not safe as it assumes p
is a Type of NavigationPage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With