[英]Creating Click Events on Programmatically Added Menu Items?
Screenshot: 截图:
I populated the above menu in screenshot using below code, but silly me I can't figure out how can I create click event on each subitem since they don't have property name? 我使用下面的代码在屏幕截图中填充了上面的菜单,但是愚蠢的我无法弄清楚如何在每个子项目上创建点击事件,因为它们没有属性名称? :S My intention is to click, let say, "Do and Do", then the file will be opened using
Process.Start(filename);
:S我的目的是点击,然后说“Do and Do”,然后使用
Process.Start(filename);
打开Process.Start(filename);
. 。 Please bear with me as I am very new to programming.
请耐心等待,因为我对编程非常陌生。 :|
:| Thank you so much!
非常感谢!
private void loadViewTemplates(string path)
{
foreach (string file in Directory.GetFiles(path, "*.txt"))
{
ToolStripItem subItem = new ToolStripMenuItem();
subItem.Text = Path.GetFileNameWithoutExtension(file);
viewTemplatesToolStripMenuItem.DropDownItems.Add(subItem);
}
}
Try stubbing out the click procedure. 尝试删除点击程序。 The sender would be the menu item that was clicked:
发件人将是被点击的菜单项:
private void MenuClicked(object sender, EventArgs e) {
MessageBox.Show("Clicked on " + ((ToolStripMenuItem)sender).Text);
}
Then wire up the click event for each menu: 然后为每个菜单连接点击事件:
ToolStripItem subItem = new ToolStripMenuItem();
subItem.Click += MenuClicked;
subItem.Text = Path.GetFileNameWithoutExtension(file);
viewTemplatesToolStripMenuItem.DropDownItems.Add(subItem);
I don't really do windows forms, so there may be a more universally accepted way to do this, but what you want to do here is add an event handler to the "click" event. 我并不真正做Windows窗体,因此可能有一种更普遍接受的方式来执行此操作,但您要在此处执行的操作是向“click”事件添加事件处理程序。 Like this:
像这样:
subItem.Click += new EventHandler(subItem_Click);
where subItem_Click
would look like this: 其中
subItem_Click
如下所示:
private void subItem_Click(object sender, EventArgs e)
{
//click logic goes here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.