Close
Topic : User Interface » Xamarin.Forms » Master Detail Page:



Master-DetailPage:

The Xamarin.Forms MasterDetailPage is the page that manages two related pages of Information. The Master Page Contain Items and the Detail Page contain detail about the items present on the master page.


Master Detail Page: infobrother

A master page typically contain the hyperlink of Detail pages. selection one of the link will navigate to the corresponding detail page. A master page contains the item, and the detail page contains the description of the item present on master page.

A MasterDetailPage Is designed to be a root page, and the result would be unexpected, if we try to use the MasterDetailPage as a child page in other pages.



Creating a MasterDetailPage:

A MasterDetailPage contains Master and Detail Properties that are both of type Page. and it is used to get and set the Master and Detail Pages Respectively. We will Create the Master-detail page step-by-step with no skip steps. We will create this application using the following steps:





Create New Project: infobrother
  • » Step 1: Creating MasterDetailPage:

    1 » Open your Visual studio, and create the New Project. In New Project window, Open Visual C# » Cross-Platform. and select cross-platform app (xamarin.forms)
    2 » Assign MasterDetail_Page name to project, browse the location where you want to store the project, and click Ok.
    3 » In New Cross-platform App window, select Blank app template.
    4 » We are creating this app for only "Android" platform, Using "Xamarin.forms" UI technology and ".NET standard" code sharing strategy.




» Step 2: Creating MasterDetailPage:

First of all, we need to create the MasterDetailPage to sets the Master and Detail Properties. Open your MasterDetail_Page MainPage.XAML file and write the given code to create the MasterDetailPage that sets the Master and Detail Properties:


<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:local="clr-namespace:MasterDetail_Page"
                 x:Class="MasterDetail_Page.MainPage">

    <!--Set Master Page Properties-->
    <MasterDetailPage.Master>
        <local:MasterPage x:Name="masterPage"/>
    </MasterDetailPage.Master>

    <!--Set Detail Page Properties.-->
    <MasterDetailPage.Detail>
        <NavigationPage>
            <x:Arguments>
                <local:HomePage/>  <!--Its front Detail Page Or home page-->
            </x:Arguments>
        </NavigationPage>
    </MasterDetailPage.Detail>
    
</MasterDetailPage>
public class MainPage : MasterDetailPage
{
    MainPage masterpage;
    public MainPage()
    {
        masterPage = new MasterPage();
      
        //set Master Page Properties:
        Master = masterPage;

        //Set Detail Page Properties:
        Detail = new NavigationPage(new HomePage());
    }
}

In Above Code, We Set the Master property to a "masterPage" that is a Content Page instance. and the Detail Page property is set to a Navigation Page containing a Content Page instance.


NOTE: The Master page should always be a Content Page Instance, and the Detail Page should Only be Populated with Tabbed Page or Navigation Page and the Content Page instance.


» Step 3: Creating Master Page:

Now we need to create the Master Page, we will Add some element in Master Page Using List View that will Populated with its Detail by setting its ItemsSource property to an array of MasterPageItem Instance. The MasterPageItem is the class and each MasterPageItem Instance defines Three Properties - Title, IconSource, and TargetType Properties.

Consider the following code, where we create the Master page, and add four Items in the list using the ItemsSource Property.


<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MasterDetail_Page.MasterPage"
             xmlns:local="using:MasterDetail_Page"
             Padding="0, 40, 0, 0"
             Icon="icon.png"
             Title="InfoBrother">
 
        <StackLayout>
        <ListView x:Name="listView">
            <ListView.ItemsSource>
                <x:Array Type="{x:Type local:MasterPageItem}">
                    <local:MasterPageItem 
                        Title="Home" 
                        IconSource="icon.png"  
                        TargetType="{x:Type local:HomePage}"
                    />
                    
                    <local:MasterPageItem 
                        Title="Tutorial" 
                        IconSource="tutorial.png"  
                        TargetType="{x:Type local:TutorialPage}"
                    />
                    
                    <local:MasterPageItem 
                        Title="About" 
                        IconSource="about.png" 
                        TargetType="{x:Type local:AboutPage}"
                    />
                    
                    <local:MasterPageItem 
                        Title="Contact" 
                        IconSource="contact.png" 
                        TargetType="{x:Type local:ContactPage}"
                    />
                </x:Array>
                
            </ListView.ItemsSource>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid Padding="5,10">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="30"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <Image Source="{Binding IconSource}"/>
                            <Label Grid.Column="1" Text="{Binding Title}"/>
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        </StackLayout>

</ContentPage>
using System;
using System.Collections.Generic;
using Xamarin.Forms;

namespace Master_Detailpage
{
	
   public partial class MasterPage : ContentPage
   {
       public ListView Listview { get { return listView; } }
       
       public MasterPage ()
       {
	  InitializeComponent ();

          var masterPageItem = new List<MasterPageItem>();
          masterPageItem.Add(new MasterPageItem
          {
              Title = "HomePage",
              IconSource = "home.png",
              TargetType = typeof(HomePage)
          });

          masterPageItem.Add(new MasterPageItem
          {
             Title = "TutorialPage",
             IconSource = "tutorial.png",
             TargetType = typeof(TutorialPage)
          });

          masterPageItem.Add(new MasterPageItem
          {
             Title = "AboutPage",
             IconSource = "about.png",
             TargetType = typeof(AboutPage)
          });

          masterPageItem.Add(new MasterPageItem
          {
             Title = "ContactPage",
             IconSource = "contact.png",
             TargetType = typeof(ContactPage)
          });

          listView = new ListView
          {
             ItemsSource = masterPageItem,
             ItemTemplate = new DataTemplate(() =>
              {
                 var grid = new Grid { Padding = new Thickness(5, 10) };
                 grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(30) });
                 grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Star });

                 var image = new Image();
                 image.SetBinding(Image.SourceProperty, "IconSource");
                 var label = new Label { VerticalOptions = LayoutOptions.FillAndExpand };
                 label.SetBinding(Label.TextProperty, "Title");

                 grid.Children.Add(image);
                 grid.Children.Add(label, 1, 0);

                 return new ViewCell { View = grid };
           }),

           SeparatorVisibility = SeparatorVisibility.None
      };

      Icon = "icon.png";
      Title = "InfoBrother";
      Content = new StackLayout
       {
           Children = { listView }
       };
     }
   }
}

In Above Code, we Assigned a DataTemplate to the ItemTemplate property to display each MasterPageItem. DataTemplate is the template for Multiple Bindings. The DataTemplate contains a ViewCell that consist of Image and a Label. The Image Show the IconSource Property Value and the Label Shows the Title Property Value for each MasterPage Item.



» Step 4: Creating Class to Get and Set the Master Page Items:

Next we need to create the Class to get and set the Master Page Items: Follow the given steps to create the MasterPageItems class.



Create MasterPagesItems Class: infobrother
  • 1 » From Solution Explorer, Right click On your Project and Add » Class.
    2 » Select Visual C# Items » Class Named it "MasterPageItem.cs" and add it in your project.

    In the Class, right the following code to get and set the Master Page Items.


using System;


namespace MasterDetail_Page
{
    class MasterPageItem
    {
        public string Title { get; set; }

        public string IconSource { get; set; }

        public Type TargetType { get; set; }
    }
}


The MasterPageItem class will set Three things for each of the Master Page Item. The Title, the Icon and the Link to its Detail Page. The Master Page has set The Title and Icon Properties. The Icon will appear on the Detail Page. Now Our Master Page has been created, the following Screenshots show the Master Page on Android Platform.


MasterPage Demo: infobrother

» Step 5: Creating & Displaying the Detail Page:

Finally we need to create Detail page of the Items present in Master page and then linked it with that item. The MasterPage Instance Contains the ListView property That Expose its Instance so that the MainPage instance can Register an Event-handler to handle the ItemSelected Event. It will Enables the MainPage Instance to set the Detail Property to the page that represents the selected list view item.

In order to Create the Detail Page and create the event handler, follow the given steps:



Create DetailPage: infobrother
  • 1 » Right click on your project and Add » New Item.
    2 » Select the Content Page from Visual C# Items tab.
    3 » Give it a name - It is the name for your detail page. and use the same name that we set using TargetType property while creating our Master Page in Step # 3. and add it in your project.


Using above Steps, create the detail pages for all the items that are present in Master page. design your detail and then Open MainPage.xaml.cs file to create the Event Handler. use the Following code to create the event handler.


using System;
using Xamarin.Forms;

namespace Master_Detailpage
{
   public partial class MainPage : MasterDetailPage
   {
	public MainPage()
	{
            InitializeComponent();

            masterPage.Listview.ItemSelected += OnItemSelected;
	}

        private 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;
            }
        }
     }
}

In Above code, We create the Method OnItemSelected() to retrieves the SelectedItems from the ListView Instance. If the selected Item is not Null, mean if there is Detail Page connected with the item, then OnItemSelected() will retrieve the Selected item's detail. In Simple, we will click on the link, and it will open its connected page. Next, In ListView, we will set the Selected Item to NULL to ensure that none of the ListView Items Will Be selected Next time the MasterPage Is Presented.

We Use IsPresented Property to display the master page or detail page. This Property control whether the display page is presented or Master Page. If we want to Display the Master Page, then we should set this property true, and if we want to display the detail page, then we set this property false

Now Our Master-Detail is ready to use. The following Screenshots show the Master-detail page on Android Platform.


Master Detail Page Template: infobrother

Control the Detail Page Display Behaviour:

How the MasterDetailPage will Manages the Master and Detail Pages is depend on Displaying device where the application is running. Is it running on Phone, or Tablet, the Orientation is Portrait or Landscape, these all things matter. All Platform define the way to handle the Master and detail page. But we can change it using the MasterBehaviour Property. This Property determines how the detail page will be displayed. The Possible values for this properties are -


ValueDescription
DefaultThe pages will displayed using the Platform Default.
PopoverThe detail Page will Covers, or Partially covers the Master Page.
SplitThe Master page will displayed on the left side and the detail page on the right side.
SplitOnLandscapeUse Split Screen, when the Orientation is Landscape.
SplitOnPortraitUse Split Screen, When the Orientation is Portrait.

We Add this property in our Main Page. The following code Demonstrates how to set the MasterBehaviour Property on our MasterDetailPage that is MainPage.


<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Master_Detailpage"
             x:Class="Master_Detailpage.MainPage"
             MasterBehavior="Popover">
   
   <!--Childs-->

</MasterDetailPage>
using System;
using Xamarin.Forms;

namespace Master_Detailpage
{
   public partial class MainPage : MasterDetailPage
   {
	public MainPage()
	{
            MasterBehavior = MasterBehavior.Popover;
	}
   }
}

The Value of the MasterBehaviour Property only effects applications running on tablets or the desktop. Applications running on Phones always have the Popover Behaviour.



















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement