A menu control is a group of menu items. Each menu item can be used for a certain action. The code samples in this article show how to use a menu control and menu items in a WPF app at design time using XAML.
The following code snippet in XAML creates a menu control at design time.
- <Menu Height="22" Name="menu1" Width="200" Margin="10, 10, 5, 5" HorizontalAlignment="Left" VerticalAlignment="Top" Background="Chocolate">
- </Menu>
The following code snippet sets a menu property.
- <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>
The following XAML adds three child menu items to the 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 following.
A separator is used to separate categories of menu items. We can add a separator to a menu control using the
<Separator /> tag.
We can also add sub menus and sub menu items using the
MenuItem tag within the 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 the following.
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 the following.
The
InputGestureText property is used to add keyboard shortcuts to the menu item. The following code adds
CTRL+O to a menu item.
- <MenuItem IsCheckable="true" Header="_Open" InputGestureText="Ctrl+O">
The Click event adds 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 as in the 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");
- }