C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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" 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> Example code: C# 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 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.