Creating MenuItem With WPF


Let us talk about "DockPanel" Which defines an area where you can arrange child elements either horizontally or vertically, relative to each other.

 

The position of child elements of a DockPanel on the screen is determined by the Dock property of the respective child elements and the relative order of those child elements under the DockPanel. Therefore, a set of child elements with the same Dock property values can be positioned differently on the screen depending on the order of these children under the DockPanel. Child ordering effects positioning because the DockPanel iterates through its child elements in order, setting the position of each element depending on remaining space.

 

Following Example illustrate File Menu for the application which has "New Contact" & "CloseMe"

 

A MenuItem can be:

  • Selected to invoke commands
  • Separators
  • Headers for submenus
  • Checked or unchecked

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

 x:Class="AddressBook.Window1" Name="AddressBook" 

 Title="Address Book" 

 SizeToContent="WidthAndHeight" Width="645">

 <Grid Background="#FFFFFFFF" Name="DocumentRoot" Width="640" Height="480">

  <!-- Menu Bar -->

  <DockPanel Name="DockPanel_Menu"

     Grid.Column="0"

     Grid.ColumnSpan="1"

     Grid.Row="0"

     Grid.RowSpan="1"

     Margin="1,0,0,0"

     HorizontalAlignment="Stretch"

     VerticalAlignment="Top"

     Width="Auto" Height="28">

    

  <DockPanel Name="DockPanel_Menu"

     Grid.Column="0" Grid.ColumnSpan="1"

     Grid.Row="0" Grid.RowSpan="1"

     HorizontalAlignment="Stretch"

     VerticalAlignment="Top" 

     Height="25" Background="White">

     

    <MenuItem Header="File">

     <MenuItem Header="New Contact" Click="ShowContact">

      <MenuItem.ToolTip>

       <ToolTip>

        Click here to add contact

       </ToolTip>

      </MenuItem.ToolTip>

     </MenuItem>

     <Separator />

     <MenuItem Header="Exit" InputGestureText="Alt-F4" Click="CloseMe">

      <MenuItem.ToolTip>

       <ToolTip>

        Click here to exit

       </ToolTip>

      </MenuItem.ToolTip>

     </MenuItem>

    </MenuItem>

   </Menu>

  </DockPanel> 

 </Grid>

</Window>

 

Here is small code snippet you can use for generating menu programmatically.

 

menu = new Menu();

menu.Background = Brushes.LightBlue;

mi = new MenuItem();

mi.Width = 50;

mi.Header = "_File";

menu.Items.Add(mi);