Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

WPF Menu Example: MenuItem and Separator

This WPF tutorial uses the Menu, MenuItem and Separator controls to create a menu bar. It uses the Click event handler.

Menu. A Menu provides common commands in a program.

In WPF, we combine elements to create a menu bar. We use the Menu control as a container for MenuItem and Separator elements. A MenuItem also can have nested MenuItems.

Example. To begin, please drag a Menu control to your program. The Menu is a container. In it, we can add MenuItem elements. Please resize your Menu—if you remove the Height attribute, the default size is used.

Next, right-click on the Menu element in Visual Studio to add MenuItems. The first MenuItems you add are the top-level menus. You can also add child MenuItem elements to those MenuItems.

Click: Add Click attributes to the innermost MenuItems. You can do this by typing Click in the XAML part of Visual Studio.

Header: The Header attribute is the text that is shown. For commands that show a dialog box, three periods (an ellipsis) is standard.

Separator: A Separator too can be added. You will probably need to adjust the height of the Separator—removing it makes it the default.

Example markup: XAML

<Window x:Class="WpfApplication21.MainWindow"
	Title="MainWindow" Height="350" Width="525">
	<Menu HorizontalAlignment="Left" VerticalAlignment="Top" Width="517">
	    <MenuItem Header="Info">
		<MenuItem Header="One..." HorizontalAlignment="Left" Width="140"
		<MenuItem Header="Two..." HorizontalAlignment="Left" Width="140"
		<Separator HorizontalAlignment="Left" Width="140"/>
		<MenuItem Header="Three..." HorizontalAlignment="Left" Width="140"

Example code: C#

using System.Windows;
using System.Windows.Controls;

namespace WpfApplication21
    public partial class MainWindow : Window
	public MainWindow()

	private void MenuItem_Click(object sender, RoutedEventArgs e)
	    // ... Cast sender object.
	    MenuItem item = sender as MenuItem;
	    // ... Change Title of this window.
	    this.Title = "Info: " + item.Header;

Click event handler. In the C# code, we see the MenuItem_Click event handler. We cast the sender object to the MenuItem type—this allows us to access its Header property, a string. We set the Window Title to one based on the Header.


Note: The same method (MenuItem_Click) is used for all the MenuItems. A different method could be used instead, if needed.

Summary. Many programs have been moving away from a traditional menu bar. But the user interface paradigm is still known and used. It is a convenient way to allow access to many commands without displaying them on the screen, all at once.