简体   繁体   中英

c# How to add an eventhandler to many menus in a foreach loop?

I'm working with the compact framework and i'm making an app for a windows mobile standard. I have an array which contain phonenumbers, and i want to add a submenu foreach number i find in that array. These submenus must be clickable, but i can't figure out how to do it.

This is my code:

             // "menuItemRight" is my main menu


             // Send a message to the person
            MenuItem smsMenu = new MenuItem();
            smsMenu.Text = "Melding";
            menuItemRight.MenuItems.Add(smsMenu);

   foreach (string Number in aPhoneNumbers)
            {
                MenuItem mNumber  = new MenuItem();

                string sNumber = Number.Trim();
                mNumber.Text = sNumber.Trim();


                //SMS
                mSMS.Text = sNumber.Trim();
                smsMenu.MenuItems.Add(mSMS);
                //mNumber.Click += new EventHandler(this.MenuClick);
            }

So what i want is a common eventhandler, but i don't know how to implement this.

Hope someone can help me :)

Thanks in advance

when the function MenuClick is called it recieves an object arg (object sender) which is the MenuItem clicked.

to have the number in this function :

string sNumber = ((MenuItem)sender).Text;
...

because you stored it in the foreach loop in that property:

mNumber.Text = sNumber.Trim();
...

Set up your event handler so it takes the phone number (or whatever data you want to pass across) as the event arguments. You'll have to derive a new event arg based class.

Thus you have one handler in which you unpack the event args to find out which item you're dealing with.

The constructor for MenuItem has what you are after ( onClick )

You can modify your loop code slightly to put some identifier into each items .Tag property, and then in your event handler, cast the sender parameter back to a MenuItem .

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM