Working With ContextMenu In Xamarin.Forms For Android Applications

Introduction
 
Menus are a common user interface component in many types of applications which are used to provide a familiar and consistent user experience.

A context menu is a floating menu that appears when the user performs a long-click on an element. It provides actions that affect the selected content or context frame.

It can also be used for navigation in your application.
 
To work with Context Menu lets create a new Xamarin Cross-platform application as follows.
 
 
 
Now, select the Blank App Template and other options as shown in the below picture.
 
 
 
Basically, I have designed this tutorial for Android Application, so I have deleted the IOS project from the Solution Explorer. Here, is the Solution Explorer as shown below.
 
 
 
Now, in MainPage.Xaml add a ListView to bind some data and create a context menu as follows.
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:ContextMenuStrip"  
  5.              x:Class="ContextMenuStrip.MainPage" BackgroundColor="#AED6F1">  
  6.       
  7.     <Label Text="Welcome to Xamarin Forms!"   
  8.            VerticalOptions="Center"   
  9.            HorizontalOptions="Center" />  
  10.   
  11.     <StackLayout>  
  12.         <Label Text="Email Details" FontSize="30" TextColor="#1C2833"></Label>  
  13.   
  14.         <ListView x:Name="myListView" HasUnevenRows="True">  
  15.             <ListView.ItemTemplate>  
  16.                 <DataTemplate>  
  17.                     <ViewCell>  
  18.                         <ViewCell.ContextActions>  
  19.                             <MenuItem Text="Detail" Clicked="OnDetail" ></MenuItem>  
  20.                             <MenuItem Text="Delete" Clicked="OnDelete"></MenuItem>  
  21.                         </ViewCell.ContextActions>  
  22.                         <Grid>  
  23.   
  24.                             <Label TextColor="Blue" Text="{Binding .}"              FontSize="25"></Label>  
  25.                         </Grid>  
  26.                     </ViewCell>  
  27.                 </DataTemplate>  
  28.             </ListView.ItemTemplate>  
  29.         </ListView>  
  30.   
  31.     </StackLayout>  
  32.   
  33.   
  34.     <!--Popup view-->  
  35.   
  36.       
  37. </ContentPage>  
 
 
Here is the Model for the Data.
  1. public class EmployeeDet  
  2.         {  
  3.             public string EmailId { getset; }  
  4.             public string FirstName { getset; }  
  5.             public string LastName { getset; }  
  6.             public string Address { getset; }  
  7.         }  
Now, here is the .cs code for Binding the data in the List View.
  1. public static List<EmployeeDet> Details()  
  2. {  
  3.     List<EmployeeDet> Li = new List<EmployeeDet>();  
  4.     Li.Add(new EmployeeDet { EmailId = "[email protected]", FirstName = "Debendra", LastName = "Dash", Address = "Bangalore India" });  
  5.     Li.Add(new EmployeeDet { EmailId = "[email protected]", FirstName = "Sujit", LastName = "Tiwari", Address = "WhitField,Bangalore,India" });  
  6.     Li.Add(new EmployeeDet { EmailId = "[email protected]", FirstName = "OmPrakash", LastName = "Dash", Address = "BTM LayOut,Bangalore, India" });  
  7.     Li.Add(new EmployeeDet { EmailId = "[email protected]", FirstName = "Naresh Yadav", LastName = "Dash", Address = "BTM LayOut,Bangalore, India" });  
  8.     Li.Add(new EmployeeDet { EmailId = "[email protected]", FirstName = "Sneha hudge", LastName = "Dash", Address = "Marathalli,Bangalore, India" });  
  9.     Li.Add(new EmployeeDet { EmailId = "[email protected]", FirstName = "Mohmadd", LastName = "Dash", Address = "Electronic City,Bangalore, India" });  
  10.     Li.Add(new EmployeeDet { EmailId = "[email protected]", FirstName = "Harish Rawat", LastName = "Dash", Address = "BTM LayOut,Bangalore, India" });  
  11.     return Li;  
  12.   
  13. }  
Here, is the Method to Bind the Data in the ListView.
  1. public void BindData()  
  2.        {  
  3.            var details = MainPage.Details().Where(p => p.FirstName != null);  
  4.            lielements = new List<string>();  
  5.            foreach (var x in details)  
  6.            {  
  7.                lielements.Add(x.EmailId);  
  8.            }  
  9.   
  10.   
  11.            myListView.ItemsSource = lielements;  
  12.   
  13.        }  
 Call this Bind Data when the application Loads-
  1. public partial class MainPage : ContentPage  
  2.     {  
  3.         List<string> lielements;  
  4.         public static List<string> deletedli = new List<string>();  
  5.   
  6.         public MainPage()  
  7.         {  
  8.             InitializeComponent();  
  9.             BindData();  
  10.   
  11.         }  
 Now, this is how the App will render.
 
 
 
This is how the Context menu appears on a long keypress on any item of the List.
 
 
 
So, here the 2 context menu appears in the app.

Now, let us perform some operation while clicking on any context menu. Let us click on Detail menu to see the details. 
  1. private void OnDetail(object sender, EventArgs e)  
  2.         {  
  3.   
  4.             var menuitem = sender as MenuItem;  
  5.             if (menuitem != null)  
  6.             {  
  7.                 string name = menuitem.BindingContext as string;  
  8.                 var details = MainPage.Details().Where(p => p.EmailId == name).FirstOrDefault();  
  9.                 DisplayAlert("Details""Name:" + details.FirstName + "\n" + "Adress:" + details.Address + "\n" + "Email:" + details.EmailId, "Cancel");  
  10.   
  11.             }  
  12.         }  
 
 
Now, just implement the Delete menu logic to temporarily remove the list.
  1. private async void OnDelete(object sender, EventArgs e)  
  2.        {  
  3.            var result = await this.DisplayAlert("Alert!""Do you really want to Delete?""Yes""No");  
  4.            if (result)  
  5.            {  
  6.                
  7.                var menuitem = sender as MenuItem;  
  8.                string name = menuitem.BindingContext as string;  
  9.   
  10.                RefreshList(name);  
  11.            }  
  12.            else  
  13.            {  
  14.   
  15.   
  16.            }  
  17.   
  18.        }  
Here is the implementation of RefreshList.
  1. public void RefreshList(string name)  
  2.         {  
  3.               
  4.             deletedli.Add(name);  
  5.             var details = MainPage.Details().ToList();  
  6.             lielements = new List<string>();  
  7.             foreach (var x in details)  
  8.             {  
  9.                 lielements.Add(x.EmailId);  
  10.             }  
  11.             foreach (var x in deletedli)  
  12.             {  
  13.                 lielements.Remove(x);  
  14.             }  
  15.               
  16.             myListView.ItemsSource = null;  
  17.             myListView.ItemsSource = lielements;  
  18.         }  
  1. public partial class MainPage : ContentPage  
  2.     {  
  3.         List<string> lielements;  
  4.         public static List<string> deletedli = new List<string>();  
  5.   
  6.         public MainPage()  
  7.         {  
  8.             InitializeComponent();  
  9.             BindData();  
  10.   
  11.         }  
 
 
Once you click on yes it will delete the following list.
 
 
 
And finally, the item will be temporarily removed from the list and shows as below.
 
 
 
Conclusion

So, in this way we can implement Context Menu in Xamarin forms applications.


Similar Articles