Share via


How to: Create a ContextMenu

This example describes how to create a ContextMenu.

The ContextMenu controls are connected to buttons and have a collection of MenuItem elements

Example

<Button Name="cmButton" Height="30">Button with Context Menu
<Button.ContextMenu>
<ContextMenu Name="cm" Opened="OnOpened" Closed="OnClosed" StaysOpen="true">
   <MenuItem Header="File"/>
   <MenuItem Header="Save"/>
   <MenuItem Header="SaveAs"/>
   <MenuItem Header="Recent Files">
        <MenuItem Header="ReadMe.txt"/>
        <MenuItem Header="Schedule.xls"/>          
   </MenuItem>
</ContextMenu>
</Button.ContextMenu>
</Button>
btn = new Button();
btn.Content = "Created with C#";
contextmenu = new ContextMenu();
btn.ContextMenu = contextmenu;
mi = new MenuItem();
mi.Header = "File";
mia = new MenuItem();
mia.Header = "New";
mi.Items.Add(mia);
mib = new MenuItem();
mib.Header = "Open";
mi.Items.Add(mib);
mib1 = new MenuItem();
mib1.Header = "Recently Opened";
mib.Items.Add(mib1);
mib1a = new MenuItem();
mib1a.Header = "Text.xaml";
mib1.Items.Add(mib1a);
contextmenu.Items.Add(mi);
cv2.Children.Add(btn);

For the complete sample see ContextMenu Sample.

See Also

Tasks

How to: Use the ContextMenuService

Concepts

ContextMenu Overview