Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » WPF » Menus in WPF

Menus in WPF

This tutorial shows you how to create and use a Menu control available in Windows Presentation Foundation (WPF).

Author Rank :
Page Views : 132312
Downloads : 2073
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WPFMenu.zip | WPF MenusTutorial.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Menus in XAML and WPF

In XAML and WPF model, the Menu and the MenuItem classes represent a menu and a menu item respectively. A Menu is a collection of menu items with a command associated with each menu items.  A menu item may have children menu items called submenus. This article discusses how to work with menus in XAML and WPF applications.

Creating a Menu as Design Time

The Menu tag in XAML creates a menu control.

The Name property defines the name of the menu and Height and Width represents the height and width of a menu control.

<Menu Name="menu1" Height="22" Width="200" />

To position a menu control in a Window, the Margin, HorizontalAlignment and VerticalAlignment properties may be used. The following code sets horizontal, vertical alignments, margin, and background color of a menu control.

<Menu Height="22" Name="menu1" Width="200" Margin="10, 10, 5, 5" HorizontalAlignment="Left" VerticalAlignment="Top" Background="Chocolate">

    </Menu>


Setting Menu Control Properties

There are three ways to set a menu control properties. You may use the Properties windows, set properties in XAML manually, or set properties at run-time using WPF code.

If you right click on the menu control and select Properties menu item, you will see the Properties window same as Figure 1.

MenuImg1.jpg 

Figure 1. Properties Window

As you can see from Figure 1, you can set all properties of a Menu control through this Window such as border thickness, opacity, bitmap effects, background and foreground colors, alignments, width and height, layouts, and fonts.

Once you set properties in the Properties window, the respective XAML code is written in the XAML file by the designer. For example, I set BorderThickness to 2, BitmapEffect to DropShadowEffect, and Background to Blue as shown in Figure 2.

MenuImg2.jpg 

Figure 2. Setting a Menu Control Properties

If you look at the XAML file now, you will see Menu code like below where you can see BorderThickness is set to 2, Background is set to Blue, and Menu.BitmapEffect tag is added within the Menu tag.

  <Menu Height="22" Name="menu1" Width="200" Margin="10, 10, 5, 5" HorizontalAlignment="Left" VerticalAlignment="Top" Background="Blue" BorderThickness="2">

        <Menu.BitmapEffect>

            <DropShadowBitmapEffect />

        </Menu.BitmapEffect>

    </Menu>

Now, the menu looks like Figure 3.

MenuImg3.jpg 

Figure 3. Menu with blue background and drop shadow effect

Adding Menu Items and Sub Menus to a Menu

Now let's add menu items and sub menus to the menu control. The MenuItem tag adds a menu item to the menu control. The following code shows the initial syntax of the MenuItem tag. The Header attribute is the name of the MenuItem.

  <MenuItem Header="Menu Item Name " />    

A MenuItem can have other MenuItem tags within it as child/sub menus and can go up to several levels. The following code adds three children menu items to first menu item.

  <MenuItem Header="_File">          

            <MenuItem Header="_Open" IsCheckable="true"/>

            <MenuItem Header="_Close" IsCheckable="true"/>

            <MenuItem Header="_Save" IsCheckable="true"/>
  </MenuItem> 

The output looks like Figure 4.

MenuImg4.jpg 

Figure 4. A menu with menu items

A separate is used to separate categories of menu items. We can add a separator to a menu control by using <Separator /> tag. 

We can also add sub menus and sub menu items using the MenuItem tag within parent a MenuItem tag. The following code adds a separator and sub menus and sub menu items to the menu.

<Separator/>

<MenuItem Header="Sub Items">

    <MenuItem Header="Child1 SubItem" IsCheckable="true"/>

    <MenuItem Header="Child2 SubItem" IsCheckable="true">

        <MenuItem Header="GrandChild2 SubItem" IsCheckable="true"/>

     </MenuItem>

</MenuItem>

 

Now, our new output looks like Figure 5.

 

MenuImg5.jpg
Figure 5. A menu with menu items

 

Adding Tooltips to Menus

The MenuItem.ToolTip tag adds a tooltip to a menu item. The following code adds a tooltip to the Open menu item.

<MenuItem Header="_Open" IsCheckable="true">

    <MenuItem.ToolTip>

        <ToolTip>

             Open a file.

        </ToolTip>

    </MenuItem.ToolTip>

</MenuItem>

The output with the tooltip looks like Figure 6.

MenuImg6.jpg 

Figure 6.  A menu with a tooltip

Adding a CheckBox to a Menu Item

By setting IsCheckable property of a MenuItem to true makes a menu item to a CheckBox in front of the header text.

<MenuItem IsCheckable="true">

MenuImg7.jpg 

Figure 7

Adding a Keyboard Shortcut to a Menu Item

InputGestureText property is used to add keyboard shortcut to the menu item. The following code adds CTRL+O to a menu item.

<MenuItem IsCheckable="true" Header="_Open" InputGestureText="Ctrl+O">

 You can also add ALT support to a menu item by adding underscore (_) before a character and ALT+character will work. For example, in the previous line of code, _Open menu item can be executed using ALT+O.


Adding an Event Trigger to a MenuItem

The Click event is used to add the menu item click event handler. The following code adds a click event handler for a menu item.

  <MenuItem IsCheckable="true" Header="_Open" Click="MenuItem_Click">

The event handler is defined like following in the code behind. I added a message box when the menu item is clicked.

private void MenuItem_Click(object sender, RoutedEventArgs e)

{

    MessageBox.Show("Menu item clicked");

}


Creating a Menu Control at Run-time

The following code creates a menu and adds menu items dynamically.

Menu mainMenu = new Menu();

mainMenu.Background = Brushes.LightGreen;

mainMenu.Height = 300;

mainMenu.Width = 200;

 

MenuItem item1 = new MenuItem();

item1.Width = 50;

item1.Header = "First";

mainMenu.Items.Add(item1);

 

MenuItem item2 = new MenuItem();

item2.Width = 50;

item2.Header = "Two";

item1.Items.Add(item2);

 

MenuItem item3 = new MenuItem();

item3.Width = 50;

item3.Header = "Third";

item1.Items.Add(item3);

Listing 1


Added on 9/27/2011

How to make a Gradient Brackground

How about creating a nice gradient background of menu looks like Figure 8.

WPFMenuColored.jpg

Figure 8

All we need is, to set the Background of the Menu item to LinearGradientBrush. 

<Menu.Background>
                     <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                           <GradientStop Color="#FF3A60AD" Offset="0.528"/>
                           <GradientStop Color="#FF6A85D8" Offset="0.01"/>
                           <GradientStop Color="#FF3464C4" Offset="1"/>
                           <GradientStop Color="#FF202E7E" Offset="1"/>
                     </LinearGradientBrush>
              </Menu.Background>

How to Add multiple menus horizontally

Let's you need to add menu items horizontally, not vertically. All you need to do is, create your Menu width so all items will fit. And you can set layout of the Grid.

WPFMenuColored.jpg

See code Listing 2. 

<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>     

       <Menu Height="38" Name="menu1" Margin="10,10,344,0" VerticalAlignment="Top" BorderThickness="2"
              Foreground="White" FontSize="16" FontWeight="Bold">

              <Menu.Background>
                     <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                           <GradientStop Color="#FF3A60AD" Offset="0.528"/>
                           <GradientStop Color="#FF6A85D8" Offset="0.01"/>
                           <GradientStop Color="#FF3464C4" Offset="1"/>
                           <GradientStop Color="#FF202E7E" Offset="1"/>
                     </LinearGradientBrush>
              </Menu.Background>
           <Menu.BitmapEffect>
               <DropShadowBitmapEffect />
           </Menu.BitmapEffect>                    

              <MenuItem Header="Tools" IsCheckable="true" >
                     <MenuItem.Icon>
                         <Image Source="Tools.png" Width="20" Height="20" />
                  </MenuItem.Icon>
              </MenuItem>                      

              <MenuItem Header="Settings" IsCheckable="true" Foreground="Orange" FontSize="16" >
                     <MenuItem.Icon>
                         <Image Source="Settings.png" Width="20" Height="20" />
                  </MenuItem.Icon>
              </MenuItem>                      

              <MenuItem Header="Security" IsCheckable="true" Foreground="White" FontSize="16">
                     <MenuItem.Icon>
                         <Image Source="Security.png" Width="20" Height="20" />
                  </MenuItem.Icon>
              </MenuItem>                      

              <MenuItem Header="Database" IsCheckable="true" Foreground="LightGreen" FontSize="16">
                     <MenuItem.Icon>
                         <Image Source="Database.png" Width="20" Height="20" />
                  </MenuItem.Icon>
                     <MenuItem.Background>
                           <ImageBrush ImageSource="Database.png" Stretch="Fill"  />
                     </MenuItem.Background>
              </MenuItem>   

    </Menu>     

</Grid> 


Listing 2

Set Menu Item Background to an Image

One of the readers asked this question, how to set the MenuItem background to an Image. 

We can do this by setting the Background property of the MenuItem to an ImageBrush. The ImageBrush takes ImageSource as the full path of an image and we can also set the Stretch property to Fill. 

<MenuItem Header="Database" IsCheckable="true" Foreground="LightGreen" FontSize="16">
       <MenuItem.Icon>
              <Image Source="Database.png" Width="20" Height="20" />
       </MenuItem.Icon>

       <MenuItem.Background>
              <ImageBrush ImageSource="Database.png" Stretch="Fill"  />
       </MenuItem.Background>
</MenuItem>   


Summary

In this article, I discussed how we can use a Menu and MenuItem controls to create menus in a WPF application.  We also saw how we can set menu properties, add menu items at design-time as well as at run-time and add menu item event handlers.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 Article Extensions
Contents added by Mahesh Chand on May 28, 2009
How to add an Image to a Menu Item.

This code adds an icon image in front of the menu item header text.

<MenuItem Header="Child1 SubItem" IsCheckable="true">

    <MenuItem.Icon>

        <Image Source="Tree.jpg" Width="20" Height="20" />

    </MenuItem.Icon>

</MenuItem>    

The output looks like this:

MenuItemWithImage.gif

 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
image as a background of menuitem by rutvij On November 6, 2008
hi .. your article is very nice. it contains lot many things about menu settings. My question is : how can we put an image as a background of menuitem? I tried through MenuItemTemplate but didn't get exact thing...
Reply | Email | Modify 
Re: image as a background of menuitem by Mahesh On May 28, 2009
Check this article extension. I just added sample code.
Reply | Email | Modify 
Re: image as a background of menuitem by Mahesh On September 27, 2011
You can use Image.Background and fill with an ImageBrush. I just updated this article.
Reply | Email | Modify 
tks by dong On March 31, 2010
A good article for beginner.thanks a lot .
Reply | Email | Modify 
Great Article but found typo by Wayne On November 19, 2010
  • This was exactly what I was looking for to add menus in WPF instead of WAF.  Thank You.
    However, I found a typo: "We can also ass sub menus" is supposed to be "We can also add sub menus".
  • Since C# is case sensitive should the following line: (IsCheckable="true") be (IsCheckable="True") 

The following is where you can find the IsCheckable="true".  This should be IsCheckable="True".  This is because C# is case sensitive.  If you search your article for IsCheckable then you should come to each one that = "true".  Simply change it to "True" to be correct.



A MenuItem can have other MenuItem tags within it as child/sub menus and can go up to several levels. The following code adds three children menu items to first menu item.

  <MenuItem Header="_File">          

            <MenuItem Header="_Open" IsCheckable="true"/>

            <MenuItem Header="_Close" IsCheckable="true"/>

            <MenuItem Header="_Save" IsCheckable="true"/>
  </MenuItem> 

The output looks like Figure 4.

AND

By setting IsCheckable property of a MenuItem to true makes a menu item to a CheckBox in front of the header text.

<MenuItem IsCheckable="true">

Reply | Email | Modify 
Re: Great Article but found typo by Mahesh On November 19, 2010
Thanks Wayne. Appreciate your comment. I did find "ass" and fixed it but could not find "True".
Reply | Email | Modify 
Reason for _? Images are gone by Wayne On November 19, 2010
Mahesh,

I posted above where the "true" is at  and why that is supposed to be "True" and not "true".
I have some other questions however.

1. Is there a reason for using the _Open, _File, _, etc etc instead of using Open, File, etc etc without the underscore?
2. Is there a specific reason for having the Open, File and Save set to IsCheckable or was this just utilized as an example that you could do this if you wanted to?

Note: None of the pictures are showing up for me now.  Figures 1 - 7 are not showing up whilst the Article Extension does show up.  I tried to right click and show image to no avail.
Reply | Email | Modify 
Re: Reason for _? Images are gone by Mahesh On November 19, 2010
OK images are fixed.

Underscore (_) is just to show how we can implement ALT in your menus. This is useful when you do not use mouse and just use the keyboard.

In C#, "true" is correct but in XAML code both "true" and "True" will work.

I think I wrote this sample with Visual Studio 2008 and now Visual Studio 2010 may change it "True" automatically.

Cheers!
Reply | Email | Modify 
Re: Reason for _? Images are gone by Mahesh On November 19, 2010
And yes, checkbox in front of menu items is also to show how to add a checkbox.
Reply | Email | Modify 
Just comments by Wayne On November 19, 2010
Thank you for your quick response.  Yes 2010 will not allow you to utilize "true".  In fact, when I attempt to it gives me errors in the XAML code.  I must utilize "True".  I will finish your article later.  You have really helped me out.  The book I am reading talks about Windows Forms and not WPF so I am attempting to convert what I am reading all over to WPF on the fly.

I read the ALT tags with an _ once before I think in the book I am reading now but it didn't click.  Thanks for the reminder.  You may want to put that in to the article so other people like me don't think it is a requirement to have it in there.  I would also let them know that you can do this if you want:

<MenuItems name="Fa_vorites"></MenuItems>

Then the v will be the ALT key.  That was awesome when I saw that.

Thanks again.
Reply | Email | Modify 
Shortcut key combination by Ivan On September 14, 2011
If i want implement a menu with a shortcut key combination, (i.e. ctrl + s)?
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.