C# 动态添加事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1531594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# dynamically add event handler
提问by Tony
Hi i have a simple question. here is my code:
嗨,我有一个简单的问题。这是我的代码:
XmlDocument xmlData = new XmlDocument();
xmlData.Load("xml.xml");
/* Load announcements first */
XmlNodeList announcements = xmlData.GetElementsByTagName("announcement");
for (int i = 0; i < announcements.Count; i++)
{
ToolStripMenuItem item = new ToolStripMenuItem();
item.Name = announcements[i].FirstChild.InnerText;
item.Text = announcements[i].FirstChild.InnerText;
/* HERE IS WERE I NEED HELP */
item.Click += new EventHandler();
this.freedomMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { item });
}
The xml LastChild holds information for each annoucement. I would like to create a click event handler where when teh list item is clicked, a message box shows up with the data inside it. My problem is i dont no how to dynamically generate event handlers to do this :(
xml LastChild 保存每个通知的信息。我想创建一个单击事件处理程序,当单击列表项时,会显示一个消息框,其中包含数据。我的问题是我不知道如何动态生成事件处理程序来做到这一点:(
采纳答案by TheVillageIdiot
try:
尝试:
/* HERE IS WERE I NEED HELP */
item.Click += new EventHandler(toolStripClick);
actual handler:
实际处理程序:
void toolStripClick(object sender, EventArgs e)
{
ToolStripItem item = (ToolStripItem)sender;
MessageBox.Show(item.Text);
}
回答by Streklin
Well, if I understand your question correctly, your "needs help" section should become this:
好吧,如果我正确理解你的问题,你的“需要帮助”部分应该变成这样:
item.Click += new EventHandler(item_click);
then you just need to add a function to your class:
那么你只需要在你的类中添加一个函数:
public void item_click(object sender, EventArgs e)
{
//do stuff here
}
回答by mcauthorn
I would recommend you look into subscriptions for events. In the event you have to make sure it's the last item in the menu item.
Look at MSDN's help for the item
我建议您查看事件订阅。如果您必须确保它是菜单项中的最后一项。
查看MSDN对该项的帮助
回答by lincolnk
are you asking for the signature for the click event? if you're working in visual studio, you should be able to type
您是否要求点击事件的签名?如果你在 Visual Studio 工作,你应该能够输入
item.Click+= tab tab
item.Click+= tab tab
and it'll generate something for you
它会为你产生一些东西
回答by Steven Robbins
You could use the Tag property of the ToolStripMenuItem:
您可以使用 ToolStripMenuItem 的 Tag 属性:
item.Tag = Announcements[i].LastChild.InnerText;
public void item_click(object sender, EventArgs e)
{
var menu = sender as ToolStripMenuItem;
if (menu!= null)
MessageBox.Show(menu.Tag);
}
Or you could use a lambda, which will capture the variable:
或者您可以使用 lambda,它将捕获变量:
string data = Announcements[i].LastChild.InnerText;
item.Click += (s, e) => { MessageBox.Show(data); };