Michael
Michael

Reputation: 1096

.NET MAUI Shell: How can `ShellContent` page be added to the navigation stack to enable "navigate back" behavior?

I have several page in MAUI Shell XAML:

    <ShellContent
        Title="Dashboard"
        ContentTemplate="{DataTemplate local:MainPage}"
        Route="MainPage">
        <ShellContent.Icon>
            <FontImageSource Glyph="&#xf0db;" FontFamily="AwesomeSolid" Color="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource Gray100}}" />
        </ShellContent.Icon>
    </ShellContent>

    <ShellContent
        Title="Ot"
        ContentTemplate="{DataTemplate local:OtherPage}"
        Route="OtherPage">
        <ShellContent.Icon>
            <FontImageSource Glyph="&#xe52f;" FontFamily="AwesomeSolid" Color="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource Gray100}}" />
        </ShellContent.Icon>
    </ShellContent>

Shell navigation works fine, but if user taps "back" on OtherPage the application will not return the user back to the main page. Also, navigation from Shell Flyout does not add a back button to the OtherPage.

If I put a button on OtherPage and try to explore navigation stack it seems like it doesn't record previous page:

private async void Button_Clicked(object sender, EventArgs e)
    {
        Console.WriteLine(Shell.Current.Navigation.NavigationStack.Count);  // prints 1

        await Shell.Current.Navigation.PopAsync();  // doesn't work

        await Shell.Current.GoToAsync("..");    // doesn't work

        await Shell.Current.GoToAsync("///MainPage"); // navigates to MainPage
    }

From the last call I can see that navigation is working, but navigating from Shell doesn't add page to the navigation stack.

How do I achieve the behavior that:

  1. Application starts on MainPage
  2. User navigates to OtherPage via Shell Flyout
  3. User taps "back" button while on OtherPage and returns to MainPage

Upvotes: 1

Views: 5534

Answers (1)

Liyun Zhang - MSFT
Liyun Zhang - MSFT

Reputation: 14639

The shell content in the Shell.Xaml will be default set as the root page in the navigation stack. In other words, when you navigates to a page via Shell Flyout, that page will be a rootpage.

And the back button will show only when you go to a page which is not added into the Shell as a flyoutitem. So both of the OtherPage and the MainPage will not show the back button when you navigation between the two pages. You navigate between the two pages with the Shell.Current.GoToAsync is same as using the Shell Flyout.

So you can remove one of the ShellContent and only use the Shell.Current.GoToAsync to navigate between the two page or only use the Shell Flyout.

Update

In the OtherPage's xaml.cs:

protected override bool OnBackButtonPressed()
{
    await Shell.Current.GoToAsync("///MainPage");
    return true;
}

Upvotes: 3

Related Questions