Add the WPF Menu, MenuItem and Separator for a menu bar. Review 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.
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.
Also, you can add child MenuItem elements to those MenuItems. 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
Title="MainWindow" Height="350" Width="525">
<Menu HorizontalAlignment="Left" VerticalAlignment="Top" Width="517">
<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#
public partial class MainWindow : Window
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.