简体   繁体   English

c#如何将事件处理程序添加到foreach循环中的许多菜单?

[英]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. 我正在使用紧凑型框架,并且正在为Windows Mobile标准开发一个应用程序。 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. 调用功能MenuClick时,它会接收到一个被单击MenuItem的对象arg(对象发送者)。

to have the number in this function : 在此功能中具有数字:

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

because you stored it in the foreach loop in that property: 因为您将其存储在该属性的foreach循环中:

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. 您必须派生一个新的基于事件arg的类。

Thus you have one handler in which you unpack the event args to find out which item you're dealing with. 因此,您有一个处理程序,您可以在其中解压缩事件args来查找要处理的项目。

The constructor for MenuItem has what you are after ( onClick ) MenuItem的构造函数具有您所追求的( 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 . 您可以稍微修改循环代码,以在每个items .Tag属性中添加一些标识符,然后在事件处理程序中,将sender参数转换回MenuItem

HTH 高温超导

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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