Dynamic Menu with Icon in WPF

In this document we are discussing about how to generate WPF menu dynamically in visual studio 2012.

Step 1: Create New Project .

wpf application

Step 2: Add Menu Control to The grid.

menu

Step 3: Create Menu

  • Include “System.Windows.Controls” in the project.
  • Create object for Menuitem.
  • Edit the properties of MenuItem.
  • Add Menu item to the Main Menu.
  1. MenuItem mnuInvoices = new MenuItem();  
  2. mnuInvoices.Header = "Invoice";  
  3. mnuInvoices.Height = 50;  
  4. this.mnuMain.Items.Add(mnuInvoices);  
Step 4: Create Sub Menu
  • Create object for Menuitem.
  • Edit the properties of MenuItem.
  • And add the submenu object to the corresponding MenuItem.
  1. MenuItem mnuInvoices = new MenuItem();  
  2. mnuInvoices.Header = "Invoice";  
  3. mnuInvoices.Height = 50;  
  4. this.mnuMain.Items.Add(mnuInvoices);  
  5.   
  6. if (ObjUsr.UserTypeid == 1)  
  7. {  
  8.       MenuItem mnuDeleteInvoice = new MenuItem();  
  9.       mnuDeleteInvoice.Header = "Delete Invoice";  
  10.       mnuDeleteInvoice.Height = 50;  
  11.       mnuInvoices.Items.Add(mnuDeleteInvoice);  
  12.   
  13.   
  14.       MenuItem mnuInvoiceStatus = new MenuItem();  
  15.       mnuInvoiceStatus.Header = "Invoice Status";  
  16.       mnuInvoiceStatus.Height = 50;  
  17.       mnuInvoices.Items.Add(mnuInvoiceStatus);  
  18. }  
  19. else  
  20. {  
  21.       MenuItem mnuInvoiceStatus = new MenuItem();  
  22.       mnuInvoiceStatus.Header = "Invoice Status";  
  23.       mnuInvoiceStatus.Height = 50;  
  24.       mnuInvoices.Items.Add(mnuInvoiceStatus);  
Step 5: Load Image Icon
  • Create Object of System.Windows.Controls.Image.
  • Assign the “System.Windows.Media.ImageSource” Path to Image Object .
  • Assign the Image object to the “Icon” Property of Menu Items.

  1. Image ObjImage = new Image();  
  2. string path = ConfigurationManager.AppSettings["AppPath"].ToString() + "/Images/pic.png";  
  3. ObjImage.Source = new BitmapImage(new Uri(path, UriKind.RelativeOrAbsolute));  
  4. mnuInvoices.Icon = ObjImage;  
menu control

Reference

Uri: http://msdn.microsoft.com/en-us/library/system.uri(v=vs.110).aspx
UriKind : http://www.c-sharpcorner.com/Forums/Thread/242530/
WPF setting a MenuItem.Icon in code

Ebook Download
View all
Learn
View all