Search code examples
c#async-awaitmaui

NavigationPage.CurrentPage is said to be a public property of the NavigationPage class in Microsoft docs, but It isn't recognized by MAUI


I want to check what page the NavigationPage is currently on, but Visual Studio says it doesn't have a definition for the CurrentPage property. It should be a feature according to Microsoft's documentation, but for some reason it doesn't work for me.

What I want to accomplish is something like below, where a second page is transfered to, and then HopOverToOtherPage waits for the user to finish with the second page before continuing.

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    public async Task<string> HopOverToOtherPage()
    {
        await Navigation.PushAsync(new SecondPage());
        while (Navigation.CurrentPage != this)  //error is thrown here
        {
            await Task.Delay(3);
        }
        return SecondPage.StaticVariable;
    }
}

The second page jumps back with await Navigation.PopAsync(); when the user decides they're finished.

App.xaml.cs code:

public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        MainPage = new NavigationPage(new MainPage());
    }
}

The only reason this is necessary, however, is that simply calling

await Navigation.PushAsync(new SecondPage());

and then letting the .blazor function that is calling the HopOverToOtherPage function assign based off of SecondPage.StaticVariable is that the program does not stop and wait for the page to switch back before continuing on, thus rendering the variable assignment outdated and inaccurate.


Solution

  • Navigation is not a NavigationPage, it is type INavigation which makes it possible to navigation.

    The simplest, maybe not most elegant, solution to what you are trying to do is: ((NavigationPage)App.Current.MainPage).CurrentPage.

    Since you're setting your MainPage to a NavigationPage you can cast it and reach the CurrentPage property on it.