FanFu FanFu - 7 days ago 5
C# Question

Create click event from WPF MenuItem defined by a string

I define parts of a menu with an array of string, and I want to automatically create click events for each of these. All of them are going to to the same thing, only a different parameter.

string[] goTos = new string[] { "First", "Second", "Third" };


When Initializing the window:

foreach (string item in goTos)
{
System.Windows.Controls.MenuItem goTo = new System.Windows.Controls.MenuItem();
goTo.Header = item;
goTo.Name = "mnu" + item;
mnuGoTo.Items.Add(goTo);
}


How can I get click events for these?

Answer

You Can try this

   string[] goTos = new string[] { "First", "Second", "Third" };
        foreach (string item in goTos)
        {
           System.Windows.Controls.MenuItem goTo = new   System.Windows.Controls.MenuItem();
            goTo.Header = item;
            goTo.Name = "mnu" + item;
            goTo.Click += new RoutedEventHandler(goTo_Click);
            mnuGoTo.Items.Add(goTo);
        }

    }

    void goTo_Click(object sender, RoutedEventArgs e)
    {
        throw new NotImplementedException();
    }