0

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?

4
  • Just add the event handler and within the event handler method determine which MenuItem called the handler by examining the sender parameter of your handler method. Commented Nov 29, 2016 at 11:29
  • Any idea how I can extract the header? Commented Nov 29, 2016 at 11:40
  • The sender object passed to your handler method is the MenuItem object. So if you use (sender as MenuItem).Header you've got all you want. (You may need to add a check for null if the handler might get called from other controls too.) Commented Nov 29, 2016 at 11:42
  • Works like a charm! Thanks! Commented Nov 29, 2016 at 11:45

2 Answers 2

1

if they are "going to to the same thing"

i suggest you use

<MenuItem Name="MenuItems" Header="Item1">
    <i:Interaction.Triggers>
           <i:EventTrigger EventName="Click">
               <ei:CallMethodAction TargetObject="{Binding}"MethodName="Event"/>
          </i:EventTrigger>
    </i:Interaction.Triggers>
</MenuItem>

on your View and add the event Method to your Viewmodel

if you do not use MVVM for your project, this is the perfect time to learn.

Sign up to request clarification or add additional context in comments.

2 Comments

I'll definitly look into it!
Make a method in your Viewmodel for the MethodName.
0

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();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.