BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Menu Controls - MenuItem

The seventy-seventh part of the Windows Presentation Foundation Fundamentals tutorial continues to describe the WPF menu controls, which present the user with a number of commands from which they may select. The second menu control is MenuItem.

Menu Icons

If you are creating a window that contains both a Menu and a ToolBar, you will often have some commands that appear in both controls. If you do, it's common to include the tool bar icon to the left of the corresponding menu item. This shows the user which button can be used instead of opening the menu.

In WPF, you can use any control for the icons. Normally you would use either a bitmap image or a vector drawing. To demonstrate, we'll add an ellipse to the left of the "View Help" menu item. To add the icon you simply set the Icon property. As this is set to another control, you must use property element syntax.

Change the XAML for the View Help menu as shown below:

<MenuItem Header="View _Help">
    <MenuItem.Icon>
        <Ellipse Width="15" Height="15" Fill="Blue"/>
    </MenuItem.Icon>
</MenuItem>

Run the program and open the Help menu to see the icon.

WPF MenuItem with icon

Richer Content

As you might imagine, WPF allows you to add other content than plain text for the menu item Header property. If you use property element syntax to declare the property, rather than a simple attribute, you can use any single control for the menu's visible content. This can include a layout control containing multiple children for complex menu options.

For the final example, we'll add some submenus to the Colour menu. Instead of showing the names of those colours, we'll display a set of Grid controls with their backgrounds set.

Replace the Colour menu's XAML with the following code:

<MenuItem Header="_Colour">
    <MenuItem>
        <MenuItem.Header>
            <Grid Background="Red" Width="100" Height="15"/>
        </MenuItem.Header>
    </MenuItem>
    <MenuItem>
        <MenuItem.Header>
            <Grid Background="Green" Width="100" Height="15"/>
        </MenuItem.Header>
    </MenuItem>
    <MenuItem>
        <MenuItem.Header>
            <Grid Background="Blue" Width="100" Height="15"/>
        </MenuItem.Header>
    </MenuItem>
</MenuItem>

Run the program and open the Format menu and the Colour submenu to see the results.

WPF MenuItem with rich content

8 July 2014