Xamarin Forms Master Detail Keep Master on the lef

2019-08-27 01:26发布

问题:

I am trying to keep the Master page (menu) to the left of My MasterDetailPage at all times, I do not want the navigation to take the user away from the MasterDetailPage and make the user press a back button to get back.

I am looking a traditional burger bar menu to the left that simply changes the Detail page and keeps the master in place.

What I have now:

public partial class App : Application
{
    public static NavigationPage NavPage { get; private set; }
    private static RootPage RootPage;
    public static bool MenuIsPresented
    {
        get
        {
            return RootPage.IsPresented;
        }
        set
        {
            RootPage.IsPresented = value;
        }
    }
    public App()
    {
        InitializeComponent();
        MenuPage menuPage = new MenuPage();
        NavPage = new NavigationPage(new FirstPage());
        RootPage = new RootPage();
        RootPage.Master = menuPage;
        RootPage.Detail = NavPage;
        MainPage = RootPage;

    }
...
}

And my ViewModel Command

async void GoSecondPageAsync(object obj)
    {
        await App.NavPage.PushAsync(new SecondPage());
        App.MenuIsPresented = false;
    }

But this just creates a new page on top of the stack with a back button back to the MasterDetailPage, while all I want is to stay within the MasterDetailPage.

回答1:

You can push the new page and just remove the first one from the NavigationStack For example:

async void GoSecondPageAsync(object obj)
{
    await App.NavPage.PushAsync(new SecondPage());
    var removePage = App.NavPage.Navigation.NavigationStack[0];
    App.NavPage.Navigation.RemovePage(removePage);
    App.MenuIsPresented = false;
}

Although, if you just always want to replace the page do you really even need the NavigationPage and can't you just set the RootPage.Detail=new SecondPage();



回答2:

You just need to update the Detail property to point to the new page. Like this:

async void GoSecondPageAsync(object obj)
    {
        RootPage.Detail = new NavigationPage(new SecondPage());
        App.MenuIsPresented = false;
    }