locked
MenuItem addHandler RRS feed

  • Question

  • I want to create a MenuItem in code. How do I add a event handler in code?


    Certified Geek. Data dude.
    Sunday, June 14, 2009 11:50 PM

Answers

  • You can add handler like this:
    XAML
    <Window x:Class="WpfApplication4.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
        <Grid>
            <Menu Name="root" Width="100" Height="75" >
                <Menu.Items>
                    <MenuItem Header="Item1" Click="MenuItem_Click"    ></MenuItem>
                </Menu.Items>
            </Menu>
        </Grid>
    </Window>
    

    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace WpfApplication4
    {
        /// <summary>
        /// Interaction logic for Window1.xaml
        /// </summary>
        public partial class Window1 : Window
        {
            public Window1()
            {
                InitializeComponent();
    
                MenuItem item = new MenuItem();
                item.Header = "Item2";
                item.Click += new RoutedEventHandler(item_Click);
    
                root.Items.Add(item);
            }
    
            void item_Click(object sender, RoutedEventArgs e)
            {
                MessageBox.Show("item2 is clicked");
            }
    
            private void MenuItem_Click(object sender, RoutedEventArgs e)
            {
                MessageBox.Show("item1 is clicked");
            }
        }
    }
    
    • Proposed as answer by LiangTao Monday, June 15, 2009 12:43 AM
    • Marked as answer by Garvander Monday, June 15, 2009 2:49 AM
    Monday, June 15, 2009 12:42 AM