Terje Isaksen Developer blog

2010-02-11 (Thursday)

WPF Menus in code

Filed under: Developing — Terje Isaksen @ 12:14
Tags: , ,

A menu is created in XAML with

<Menu Height="22" Name="menu1" VerticalAlignment="Top" >
            <MenuItem Header="Alfa" ><MenuItem>
</Menu>

To do this in code:

public MenuItem MakeMenu()  {
        MenuItem mmm1 = new MenuItem();    mmm1.Header = "Subsubmenu";
        mmm1.Click += new RoutedEventHandler( mmm1_Click );
        MenuItem mm1 = new MenuItem();        mm1.Header = "Submenu";        mm1.Items.Add( mmm1 );
        MenuItem m1 = new MenuItem();        m1.Header = "Menu";        m1.Items.Add( mm1 );

return m1;
}
void mmm1_Click( object sender , RoutedEventArgs e )     {         MessageBox.Show( "Hepp" );        }

and then in the constructor of the window:

 public Window1()        {
         InitializeComponent();
         menu1.Items.Add( MakeMenu() );
}
Advertisements

Blog at WordPress.com.