How can I create a drawer / slider menu with Xamarin.Forms?

You create a new class which contains all the definitions for both the Master – i.e. the menu – and the Detail – i.e. the main page. I know, it sounds back-to-front, but for example..

using System;
using Xamarin.Forms;

namespace testXamForms
 {
   public class HomePage : MasterDetailPage
   {
   public HomePage()
   {
     // Set up the Master, i.e. the Menu

     Label header = new Label
     {
       Text = "MENU",
       Font = Font.BoldSystemFontOfSize(20),
       HorizontalOptions = LayoutOptions.Center
     };
    // create an array of the Page names
     string[] myPageNames = {
       “Main”,
       “Page 2”,
       “Page 3”,
     };

     // Create ListView for the Master page.
     ListView listView = new ListView
     {
       ItemsSource = myPageNames,
     };

     // The Master page is actually the Menu page for us
    this.Master = new ContentPage
     {
       Title = "The Title is required.",
       Content = new StackLayout
       {
         Children = 
         {
           header, 
           listView
         },
       }
     };

     // Define a selected handler for the ListView contained in the Master (ie Menu) Page.

     listView.ItemSelected += (sender, args) =>
     {
       // Set the BindingContext of the detail page.
       this.Detail.BindingContext = args.SelectedItem;
        Console.WriteLine("The args.SelectedItem is
       {0}",args.SelectedItem);


     // This is where you would put your “go to one of the selected pages” 

       // Show the detail page.
       this.IsPresented = false;
     };
    // Set up the Detail, i.e the Home or Main page.
     Label myHomeHeader = new Label
     {
       Text = "Home Page",
       HorizontalOptions = LayoutOptions.Center
     };

     string[] homePageItems = { “Alpha”, “Beta”, “Gamma” };
     ListView myHomeView = new ListView {
       ItemsSource = homePageItems,
     };

     var myHomePage = new ContentPage();
     myHomePage.Content = new StackLayout
     {
       Children = 
       {
         myHomeHeader, 
         myHomeView
       } ,
     };
     this.Detail = myHomePage;
   }  
   }
 }

Leave a Comment