Home
WPF
Menu, MenuItem and Separator
Updated Apr 15, 2025
Dot Net Perls
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.
To begin, please drag a Menu control to your WPF program. The Menu is a container. Right-click on the Menu element in Visual Studio to add MenuItems.
Example code. We 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.
Info The Header attribute is the text that is shown. For commands that show a dialog box, three periods (an ellipsis) is standard.
Also A Separator can be added. You will probably need to adjust the height of the Separator—removing it makes it the default.
<Window x:Class="WpfApplication21.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Menu HorizontalAlignment="Left" VerticalAlignment="Top" Width="517"> <MenuItem Header="Info"> <MenuItem Header="One..." HorizontalAlignment="Left" Width="140" Click="MenuItem_Click"/> <MenuItem Header="Two..." HorizontalAlignment="Left" Width="140" Click="MenuItem_Click"/> <Separator HorizontalAlignment="Left" Width="140"/> <MenuItem Header="Three..." HorizontalAlignment="Left" Width="140" Click="MenuItem_Click"/> </MenuItem> </Menu> </Grid> </Window>
using System.Windows; using System.Windows.Controls; namespace WpfApplication21 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } 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 MenuItem_Click. We cast the sender object to the MenuItem type—this allows us to access its Header property, a string.
Note The same method (MenuItem_Click) is used for all the MenuItems. A different method could be used instead, if needed.
A menu allows access to many commands without displaying them all on the screen. The Menu control in WPF is easy to add to a program and fill with menus.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 15, 2025 (edit).
Home
Changes
© 2007-2025 Sam Allen