Search code examples
navigationmaui.net-maui

How can I use Navigation.PushAsync from a FlyoutPage?


All I want is a main page on app startup, with a flyout menu. In that flyout menu, are links to other pages. On those pages, they should have a back button that takes you back to the main startup page. (Along with the hardware back button)

The navigation stack should only ever be two pages. The MainPage, and whatever choice from the flyout menu.

I'm not using AppShell, that was a headache in of itself. I've MacGyver'd up a flyout page from various reference docs and videos on the subject. I have a MainPage with a button that PushAsync's to Page2 with no problem, back button goodness all around.

The flyout menu works in the sense that MainPage has the burger icon and it flies out with menu options. However that's where it stops working. It seems the only way to navigate to a new page is to use:

NewPage = new NavigationPage(new Page2());

Using this method, when you click a link to another page, the flyout closes, it loads up the page, but it has the burger icon instead of the back button. (I'm assuming because it wasn't pushed to the stack...)

I've tried using variations of Navigation.PushAsync(new Page2()); to no avail. When I click/tap a page link in the flyout menu, nothing happens and the flyout menu stays open. I verified the code was actually running using breakpoints.

I've uploaded the project to GitHub if someone wants to take a look. :)


Solution

  • this works for me - it could probably be simplified, and definitely needs exception handling

    void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var item = e.CurrentSelection.FirstOrDefault() as FlyoutPageItem;
        
        if (item != null)
        {
            // create the new page
            var newpage = ((Page)Activator.CreateInstance(item.TargetType));
    
            // get the navigation page
            var nav = (NavigationPage)Detail;
            
            // get the current displayed page
            var page = (ContentPage)nav.CurrentPage;
            
            // navigate to the new page
            page.Navigation.PushAsync(newpage);
    
            // hide the flyout
            this.IsPresented = false;
        }
    }