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
.
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.
<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; } } }
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
.
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.