Obtain current page name in Xamarin Forms app

19,036

Solution 1

This is just C# reflection - the name of the XAML page should match the name of it's class

var name = this.GetType ().Name;

Solution 2

You would (commonly) use wither a one page app (master/detail, tabs page) or a set of navigable pages, managed by a NavigationPage. App.Current.MainPage would (normally) contain the first page shown and if it has .Navigation that would be the NavigationPage that can give you the most recently shown page - last one in the stack. If it doesn't you could assume your app being one page app.

All of the above is just "common" and not necessarily true in all cases, but gives you a starting point where to look for your current page.

var actionPage = App.Current.MainPage;
if (actionPage.Navigation != null)
    actionPage = actionPage.Navigation.NavigationStack.Last();
actionPage.DisplayActionSheet(...)

Solution 3

I know that this has been resolved and the scenario is somewhat different but in my specific case I needed to identify the current page in the navigation stack from platform specific code so just in case it may help someone else, this is the code I used:

I used the title property that was set in the constructor of the page.

public static string GetCurrentPage()
        {
            var page = App.Navigation.NavigationStack.Last();
            return page.Title;
        }

Solution 4

You can get current open page.

1) if it's MainPage. -> var MainPage = App.Current.MainPage as PageName;

2) if it's Navigation page.

you can get count pages.

App.Current.MainPage.Navigation.ModalStack.Count

var page= App.Current.MainPage.Navigation.ModalStack.LastOrDefault() as 

PageName;

App.Current.MainPage.Navigation.NavigationStack.Count

var page1=App.Current.MainPage.Navigation.NavigationStack.LastOrDefault() as 
PageName; 
Share:
19,036
Guido Magrin
Author by

Guido Magrin

23, Xamarin and Microsoft Student Partner. CEO & Founder of HeartWatch. Passionate of C# development.

Updated on June 26, 2022

Comments

  • Guido Magrin
    Guido Magrin about 2 years

    I am currently trying to understand how to get the name of the (xaml) page I am currently into, with my Xamarin Form app.

    How am I supposed to do it? I tried a variety of cases, even looking around the Internet, but nothing actually worked for me so far :/