Show "Back to Menu" Button in iOS NavigationBar with Xamarin.Forms

Falko picture Falko · Jul 11, 2014 · Viewed 12.5k times · Source

I'm trying to build a cross-platform app using C# and Xamarin.Forms. It contains a slide-out menu implemented in form of a MasterDetailPage. While on Android there is a button with the app icon in the top left corner, which toggles the slide-out page, there is no such navigation bar item on iOS.

I broke it down to the following minimum example derived from the Xamarin solution template "Blank App (Xamarin.Forms Shared)" and replacing the implementation of the App-class:

public class App
{
    static MasterDetailPage MDPage;

    public static Page GetMainPage()
    {
        return new NavigationPage(
            MDPage = new MasterDetailPage {
                Master = new ContentPage {
                    Title = "Master",
                    Content = new StackLayout {
                        Children = { Link("A"), Link("B"), Link("C") }
                    },
                },
                Detail = new ContentPage { Content = new Label { Text = "A" } },
            });
    }

    static Button Link(string name)
    {
        var button = new Button { Text = name };
        button.Clicked += delegate {
            MDPage.Detail = new ContentPage { Content = new Label { Text = name } };
            MDPage.IsPresented = false;
        };
        return button;
    }
}

The solution as well as resulting screenshots can be found at GitHub.

My idea was to add such a "menu" or "back" button in the iOS-specific code modifying the window.RootViewController.NavigationController.NavigationBar within the AppDelegate class. But window.RootViewController.NavigationController is null.

Replacing the return type of GetMainPage() by NavigationPage instead of Page does not help.

I could add toolbar items via MDPage.ToolbarItems.Add(...), but they appear in the top right corner.

Answer

Chase Florell picture Chase Florell · Jul 15, 2014

TL;DR

Essentially, your Detail page needs to be wrapped in a NavigationPage for the back button to appear in iOS.


Here's an example of how I structure my apps.

App.cs

    public static INavigation Navigation { get; set; }

    public static Page GetMainPage(IContainer container)
    {
        return new MainPage();
    }

MainPage.cs

public class MainPage : MasterDetailPage
{

    public MainPage()
    {
        Title = "Some Title";
        var master = new MainMenu();
        var detail = new NavigationPage(new FirstPage());

        if (App.Navigation == null)
        {
            App.Navigation = detail.Navigation;
        }

        Master = master;
        Detail = detail;
    }
}

Now that you've done this, your Navigation Drawer will behave as expected, and so will your ActionBar.

When you want to navigate throughout the app, you use the statically defined Navigation

await App.Navigation.PushAsync(new FooPage());
// or
await App.Navigation.PopAsync();