Master-Detail Page

Navigating between related pages

PDF for offline use
Sample Code:
Related Articles:
Related APIs:

Let us know how you feel about this

Translation Quality


0/250

The Xamarin.Forms MasterDetailPage is a page that manages two related pages of information – a master page that presents items, and a detail page that presents details about items on the master page. This article demonstrates how to use a MasterDetailPage and navigate between its pages of information.

Overview

A master page typically displays a list of items, as shown in the following screenshots:

The location of the list of items is identical on each platform, and selecting one of the items will navigate to the corresponding detail page. In addition, the master page also features a navigation bar that contains a button that can be used to navigate to the active detail page. The location of the navigation bar is platform dependent:

  • On iOS, the navigation bar is present at the top of the page and has a button that navigates to the detail page. In addition, the active detail page can be navigated to by swiping the master page to the left.
  • On Android, the navigation bar is present at the top of the page and displays a title, an icon, and a button that navigates to the detail page. The icon is defined in the [Activity] attribute that decorates the MainActivity class in the Android platform-specific project. In addition, the active detail page can be navigated to by swiping the master page to the left, by tapping the detail page at the far right of the screen, and by tapping the Back button at the bottom of the screen.
  • On Windows Phone, the navigation bar is present at the bottom of the page and has a button that navigates to the detail page. In addition, the active detail page can be navigated to by tapping the Back button at the bottom of the screen.

A detail page displays data that corresponds to the item selected on the master page, and the main components of the detail page are shown in the following screenshots:

The detail page contains a navigation bar, whose location is platform dependent:

  • On iOS, the navigation bar is present at the top of the page and displays a title, and has a button that returns to the master page, provided that the detail page instance is wrapped in the NavigationPage instance. In addition, the master page can be returned to by swiping the detail page to the right.
  • On Android, a navigation bar is present at the top of the page and displays a title, an icon, and a button that returns to the master page. The icon is defined in the [Activity] attribute that decorates the MainActivity class in the Android platform-specific project.
  • On Windows Phone, the navigation bar is present at the bottom of the page and has a button that returns to the master page.

Navigation Behavior

The behavior of the navigation experience between master and detail pages is platform dependent:

  • On iOS, the detail page slides to the right as the master page slides from the left, and the left part of the detail page is still visible.
  • On Android, the detail and master pages are overlayed on each other.
  • On Windows Phone, the detail and master pages are swapped.

Similar behavior will be observed in landscape mode, except that the master page on iOS and Android has a similar width as the master page in portrait mode, so more of the detail page will be visible.

For information about controlling the navigation behavior, see Controlling the Detail Page Display Behavior.

Creating a MasterDetailPage

A MasterDetailPage contains Master and Detail properties that are both of type Page, which are used to get and set the master and detail pages respectively.

It's recommended that the master page of a MasterDetailPage should always be a ContentPage instance, and that the detail page should only be populated with TabbedPage, NavigationPage, and ContentPage instances. This will help to ensure a consistent user experience across all platforms.

The following XAML code example shows a MasterDetailPage that sets the Master and Detail properties:

<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  xmlns:local="clr-namespace:MasterDetailPageNavigation;assembly=MasterDetailPageNavigation"
                  x:Class="MasterDetailPageNavigation.MainPage">
    <MasterDetailPage.Master>
        <local:MasterPage x:Name="masterPage" />
    </MasterDetailPage.Master>
    <MasterDetailPage.Detail>
        <NavigationPage>
            <x:Arguments>
                <local:ContactsPage />
            </x:Arguments>
        </NavigationPage>
    </MasterDetailPage.Detail>
</MasterDetailPage>

The following code example shows the equivalent MasterDetailPage created in C#:

public class MainPageCS : MasterDetailPage
{
    MasterPageCS masterPage;

    public MainPageCS ()
    {
        masterPage = new MasterPageCS ();
        Master = masterPage;
        Detail = new NavigationPage (new ContactsPageCS ());
        ...
    }
    ...
}

The MasterDetailPage.Master property is set to a ContentPage instance. The MasterDetailPage.Detail property is set to a NavigationPage containing a ContentPage instance.

Creating the Master Page

The following XAML code example shows the declaration of the MasterPage object, which is referenced through the MasterDetailPage.Master property:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MasterDetailPageNavigation.MasterPage"
             Padding="0,40,0,0"
             Icon="hamburger.png"
             Title="Personal Organiser">
    <ContentPage.Content>
        <StackLayout VerticalOptions="FillAndExpand">
            <ListView x:Name="listView" VerticalOptions="FillAndExpand" SeparatorVisibility="None">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ImageCell Text="{Binding Title}" ImageSource="{Binding IconSource}" />
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

The page consists of a ListView, where each item in the ListView is an ImageCell that displays an image and a title. The page has its Title and Icon properties set. The icon will appear on the detail page, provided that the detail page has a title bar. This must be enabled on iOS by wrapping the detail page instance in a NavigationPage instance.

The MasterDetailPage.Master page must have its Title property set, or an exception will occur.

The ListView instance is populated with data in the code-behind file, as shown in the following code example:

public partial class MasterPage : ContentPage
{
    public ListView ListView { get { return listView; } }

    public MasterPage ()
    {
        InitializeComponent ();

        var masterPageItems = new List<MasterPageItem> ();
        masterPageItems.Add (new MasterPageItem{
            Title = "Contacts",
            IconSource = "contacts.png",
            TargetType = typeof(ContactsPage)
        });
        masterPageItems.Add (new MasterPageItem{
            Title = "TodoList",
            IconSource = "todo.png",
            TargetType = typeof(TodoListPage)
        });
        masterPageItems.Add (new MasterPageItem{
            Title = "Reminders",
            IconSource = "reminders.png",
            TargetType = typeof(ReminderPage)
        });

        listView.ItemsSource = masterPageItems;
    }
}

A MasterPageItem collection is created, with each MasterPageItem defining Title, IconSource, and TargetType properties. The IconSource and Title property values are displayed by the ImageCell for each item in the ListView instance.

The following code example shows the equivalent page created in C#:

public class MasterPageCS : ContentPage
{
    public ListView ListView { get { return listView; } }

    ListView listView;

    public MasterPageCS ()
    {
        var masterPageItems = new List<MasterPageItem> ();
        masterPageItems.Add (new MasterPageItem {
            Title = "Contacts",
            IconSource = "contacts.png",
            TargetType = typeof(ContactsPageCS)
        });
        masterPageItems.Add (new MasterPageItem {
            Title = "TodoList",
            IconSource = "todo.png",
            TargetType = typeof(TodoListPageCS)
        });
        masterPageItems.Add (new MasterPageItem {
            Title = "Reminders",
            IconSource = "reminders.png",
            TargetType = typeof(ReminderPageCS)
        });

        listView = new ListView {
            ItemsSource = masterPageItems,
            ItemTemplate = new DataTemplate (() => {
                var imageCell = new ImageCell ();
                imageCell.SetBinding (TextCell.TextProperty, "Title");
                imageCell.SetBinding (ImageCell.ImageSourceProperty, "IconSource");
                return imageCell;
            }),
            VerticalOptions = LayoutOptions.FillAndExpand,
            SeparatorVisibility = SeparatorVisibility.None
        };

        Padding = new Thickness (0, 40, 0, 0);
        Icon = "hamburger.png";
        Title = "Personal Organiser";
        Content = new StackLayout {
            VerticalOptions = LayoutOptions.FillAndExpand,
            Children = {
                listView
            }
        };
    }
}

The following screenshots show the master page on each platform:

Creating and Displaying the Detail Page

The MasterPage instance contains a ListView property that exposes its ListView instance so that the MainPage MasterDetailPage instance can register an event-handler to handle the ItemSelected event. This enables the MainPage instance to set the Detail property to the page that represents the selected ListView item. The following code example shows the event-handler:

public partial class MainPage : MasterDetailPage
{
    public MainPage ()
    {
        ...
        masterPage.ListView.ItemSelected += OnItemSelected;
    }

    void OnItemSelected (object sender, SelectedItemChangedEventArgs e)
    {
        var item = e.SelectedItem as MasterPageItem;
        if (item != null) {
            Detail = new NavigationPage ((Page)Activator.CreateInstance (item.TargetType));
            masterPage.ListView.SelectedItem = null;
            IsPresented = false;
        }
    }
}

The OnItemSelected method performs the following actions:

  • It retrieves the SelectedItem from the ListView instance, and provided that it's not null, sets the detail page to a new instance of the page type stored in the TargetType property of the MasterPageItem. The page type is wrapped in a NavigationPage instance in order to ensure that the icon referenced through the Icon property on the MasterPage is shown on the detail page in iOS.
  • The selected item in the ListView is set to null in order to ensure that none of the ListView items will be selected next time the MasterPage is presented.
  • The detail page is presented to the user by setting the MasterDetailPage.IsPresented property to false. This property controls whether the master or detail page is presented. It should be set to true to display the master page, and to false to display the detail page.

The following screenshots show the ContactPage detail page, which is shown after it's been selected on the master page:

Rather than using a MasterDetailPage on Windows Phone, a user interface class that provides an experience that is more consistent with the platform should ideally be used, such as CarouselPage.

Controlling the Detail Page Display Behavior

How the MasterDetailPage manages the master and detail pages depends on whether the application is running on a phone or tablet, the orientation of the device, and the value of the MasterBehavior property. This property determines how the detail page will be displayed. It's possible values are:

  • Default – The pages are displayed using the platform default.
  • Popover – The detail page covers, or partially covers the master page.
  • Split – The master page is displayed on the left and the detail page is on the right.
  • SplitOnLandscape – A split screen is used when the device is in landscape orientation.
  • SplitOnPortrait – A split screen is used when the device is in portrait orientation.

The following XAML code example demonstrates how to set the MasterBehavior property on a MasterDetailPage:

<?xml version="1.0" encoding="UTF-8"?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  x:Class="MasterDetailPageNavigation.MainPage"
                  MasterBehavior="Popover">
  ...
</MasterDetailPage>

The following code example shows the equivalent MasterDetailPage created in C#:

public class MainPageCS : MasterDetailPage
{
    MasterPageCS masterPage;

    public MainPageCS ()
    {
        MasterBehavior = MasterBehavior.Popover;
        ...
    }
}

However, the value of the MasterDetailPage property only affects applications running on tablets. Applications running on phones always have the Popover behavior.

Summary

This article demonstrated how to use a MasterDetailPage and navigate between its pages of information. The Xamarin.Forms MasterDetailPage is a page that manages two pages of related information – a master page that presents items, and a detail page that presents details about items on the master page.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.