Follow Us

Skip Navigation LinksHome > Articles > WPF > How to create ContextMenu and MenuItem in WPF and XAML

How to create ContextMenu and MenuItem in WPF and XAML

It explains how to create ContextMenu and MenuItem at design time and run time, their properties such as adding image and event handling

By Pankaj   On   Friday, 19 September 2008

Page Views : 138749   |   Technologies : WPF

Rating : Rated :
0
| More..

WPF ContextMenu and MenuItem Control:

 

ContextMenu is attached to a control and displayed at the right mouse click. ContextMenu contains a list of MenuItem, which represent the command or option on which user initiate an action or command.

 

In this article I would discus how to create ContextMenu and MenuItem at design time and run time, their properties and event handling.

 

Design Time Creation:

Context menu has to be in context of a control so cannot be created alone.  In the example I used Textbox but you can use any control to for which context menu can be created.

e.g.

<TextBox Name="txtControl" Height="200">

            TextBox with Context Menu

            <TextBox.ContextMenu>

                <ContextMenu Name="cm">

                    <MenuItem Header="Copy"/>

                    <MenuItem Header="Paste"/>

                    <MenuItem Header="Clear"/>

                </ContextMenu>

            </TextBox.ContextMenu>

        </TextBox>

 

Setting Menu Control Properties

There are various ways to set the control properties in WPF. You may use the Properties windows, set properties in XAML elements manually, or set properties at run-time using C# code.

If you right click on the menu control and select Properties menu item or select the control in XAML code and press the F4 key, you will see the Properties window same as Figure 1.

 

Figure 1

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

 

Once you set properties in the Properties window, the designer writes the respective XAML code in the XAML file. For example, I set BitmapEffect to OuterGlowBitmapEffect, and Background to Cornsilk as shown follows.

<ContextMenu Name="cm" StaysOpen="true" Background="Cornsilk">

                    <ContextMenu.BitmapEffect>

                        <OuterGlowBitmapEffect />

                    </ContextMenu.BitmapEffect>

                    <MenuItem Header="Copy">

                        <MenuItem.Icon>

                            <Image Source="Copy.png"/>

                        </MenuItem.Icon>

                    </MenuItem>

                    <MenuItem Header="Paste"/>

                    <MenuItem Header="Clear"/>

                </ContextMenu>

            </TextBox.ContextMenu>

 

It would look like the figure 2.

 

Figure 2

You can set the prperties of each menu item in the sam way as desired. Now you would see how to add the menu item and sub menu item in the context menu.

 

Adding Menu Items and Sub Menus to a Menu

Now let's add menu items and menus to the ContextMenu control. The MenuItem tag adds a menu item to the ContextMenu 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 caption" />    

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

  <MenuItem Header="Font Style">          

            <MenuItem Header="Under Line" IsCheckable="true"/>

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

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

IsCheckable property is used to toggle the selection of the menu. Once selected then it would be marked as checked in the next selection check mark would be cleared.

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

 

Figure 3

 

Adding the image to Menu

Adding icon is not straightforward to the menu. You have to use the Icon property in the following way in the XAML code and set the image as follows:

<MenuItem Header="Copy">

         <MenuItem.Icon>

                <Image Source="Copy.png"/>

         </MenuItem.Icon>

</MenuItem>

You have allready seen that iamge in figure 3.

Adding Tooltips to Menus

The MenuItem has ToolTip property to add the tooltip. The following code adds a tooltip to the Paste menu item.

<MenuItem Header="Paste" ToolTip="Paste the selected text to text box" />

Figure 4 shows the tooltip

 

Figure 4.

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+V to a menu item.

<MenuItem Header="Paste" ToolTip="Paste the selected text to text box" InputGestureText="Ctrl+V" />

 

Adding an Event Trigger to a MenuItem

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

  <MenuItem Header="Clear" Click="MenuItemClear_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 MenuItemClear_Click(object sender, RoutedEventArgs e)

        {

            MessageBox.Show("Menu item clicked");

            txtControl.Text = "";

        }

Creating a Menu Control at Run-time

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

ContextMenu mainMenu = new ContextMenu();

mainMenu.Background = Brushes.LightGreen;

mainMenu.Height = 300;

mainMenu.Width = 200;

 

MenuItem item1 = new MenuItem();

item1.Width = 50;

item1.Header = "Paste";

mainMenu.Items.Add(item1);

 

MenuItem item2 = new MenuItem();

item2.Width = 50;

item2.Header = "Clear";

item1.Items.Add(item2);

 

MenuItem item3 = new MenuItem();

item3.Width = 50;

item3.Header = "Copy";

item1.Items.Add(item3);

On special request I writitng code how to create menu at run time and have the icon at run time.

                  private void SampleRuntimeMenu()

        {

            ContextMenu mainMenu = new ContextMenu();

            txtControl.ContextMenu = mainMenu;

 

            MenuItem item1 = new MenuItem();

            item1.Header = "Paste";

            item1.Foreground = Brushes.Black;

            item1.Background = Brushes.Transparent;

            mainMenu.Items.Add(item1);

 

            MenuItem item2 = new MenuItem();

            item2.Header = "Clear";

            mainMenu.Items.Add(item2);

 

//create image at runtime and attach to menu at runtime

            BitmapImage copyimage = new BitmapImage();

            copyimage.BeginInit();

            Uri myUri = new Uri("Copy.png",             UriKind.RelativeOrAbsolute);

            copyimage.UriSource = myUri;

            copyimage.EndInit();

 

            Image iconImage = new Image();

            iconImage.Source = copyimage;

 

            MenuItem item3 = new MenuItem();

            item3.Header = "Copy";

            item3.Icon = iconImage;

            mainMenu.Items.Add(item3);

           

        }


Summary: In this article, I discussed the use of the Context menu and menu item 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. Most importantly we have seen how to add the image to menu item.


Keywords :
Tags :
Rate This Article :

Comments :

# 1 Annonymous Wrote on 11/19/2008


thanks a lot.



# 2 Annonymous Wrote on 03/13/2009


i have checked its not working its just the designing. its not doing anything how can i make it run



# 3 Annonymous Wrote on 05/11/2009


nice tutorial



# 4 Annonymous Wrote on 08/31/2009


How do i add icon to contextmenu at run time



# 5 Pankaj Wrote on 09/01/2009


you can use following code to create icon at run time. I am modifying the existing code in the sampleruntimemenu. private void SampleRuntimeMenu() { ContextMenu mainMenu = new ContextMenu(); txtControl.ContextMenu = mainMenu; MenuItem item1 = new MenuItem(); item1.Header = "Paste"; item1.Foreground = Brushes.Black; item1.Background = Brushes.Transparent; mainMenu.Items.Add(item1); MenuItem item2 = new MenuItem(); item2.Header = "Clear"; mainMenu.Items.Add(item2); BitmapImage copyimage = new BitmapImage(); copyimage.BeginInit(); Uri myUri = new Uri("Copy.png", UriKind.RelativeOrAbsolute); copyimage.UriSource = myUri; copyimage.EndInit(); Image iconImage = new Image(); iconImage.Source = copyimage; MenuItem item3 = new MenuItem(); item3.Header = "Copy"; item3.Icon = iconImage; mainMenu.Items.Add(item3); }



# 6 Annonymous Wrote on 10/20/2009


thanks a lot



# 7 Annonymous Wrote on 10/27/2009


Thanks but how to add event Handlers at run time for each menu item you add?



# 8 JProprio Wrote on 01/27/2011


Good Tutorial... Now I'd like to know how to add code inside of the item... for example: File->New... I wanna write some code inside of new menu.... thanks in advance... JProprio....



# 9 JProprio Wrote on 01/27/2011


Good Tutorial... Now I'd like to know how to add code inside of the item... for example: File->New... I wanna write some code inside of new menu.... thanks in advance... JProprio....




blog comments powered by Disqus
User Login
Username :
Password :
Register Login

Forgot Password


Related Articles