Menu, MenuItem and SeparatorAdd the WPF Menu, MenuItem and Separator for a menu bar. Review the Click event handler.
This page was last reviewed on Sep 27, 2022.
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.
Detail The Header attribute is the text that is shown. For commands that show a dialog box, three periods (an ellipsis) is standard.
Detail A Separator too 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 summary. 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 27, 2022 (edit).
© 2007-2024 Sam Allen.