Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms check is page is Modal

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.

like image 718
henda79 Avatar asked Oct 15 '25 02:10

henda79


2 Answers

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));
        }
    }
}
like image 177
nevermore Avatar answered Oct 18 '25 12:10

nevermore


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.

like image 24
henda79 Avatar answered Oct 18 '25 11:10

henda79



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!