Dynamic Menu in WPF

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

Step 1: Create New Project.

web application

Step 2: Add Menu Control to The grid.

toolbox

Step 3: 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.   
    3. mnuInvoices.Header = "Invoice";  
    4.   
    5. mnuInvoices.Height = 50;  
    6.   
    7. 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.   
    3. mnuInvoices.Header = "Invoice";  
    4.   
    5. mnuInvoices.Height = 50;  
    6.   
    7. this.mnuMain.Items.Add(mnuInvoices);  
    8.   
    9. if (ObjUsr.UserTypeid == 1)  
    10.   
    11. {  
    12.   
    13.       MenuItem mnuDeleteInvoice = new MenuItem();  
    14.   
    15.       mnuDeleteInvoice.Header = "Delete Invoice";  
    16.   
    17.       mnuDeleteInvoice.Height = 50;  
    18.   
    19.       mnuInvoices.Items.Add(mnuDeleteInvoice);  
    20.   
    21.       MenuItem mnuInvoiceStatus = new MenuItem();  
    22.   
    23.       mnuInvoiceStatus.Header = "Invoice Status";  
    24.   
    25.       mnuInvoiceStatus.Height = 50;  
    26.   
    27.       mnuInvoices.Items.Add(mnuInvoiceStatus);  
    28.   
    29. }  
    30.   
    31. else  
    32.   
    33. {  
    34.   
    35.       MenuItem mnuInvoiceStatus = new MenuItem();  
    36.   
    37.       mnuInvoiceStatus.Header = "Invoice Status";  
    38.   
    39.       mnuInvoiceStatus.Height = 50;  
    40.   
    41.       mnuInvoices.Items.Add(mnuInvoiceStatus);  
    42.   
    43. }  


Next Recommended Reading Dynamic Tab Control in WPF MVVM