C# 将项目动态添加到上下文菜单并设置单击操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/225394/
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
Dynamically add items to a Context Menu & set Click action
提问by Matías
I have a List of strings that is regenerated every 5 seconds. I want to create a Context Menu and set its items dynamically using this list. The problem is that I don't have even a clue how to do that and manage the Click action for every item generated (which should use the same method with different parameter DoSomething("item_name")).
我有一个每 5 秒重新生成一次的字符串列表。我想创建一个上下文菜单并使用此列表动态设置其项目。问题是我什至不知道如何执行此操作并为生成的每个项目管理 Click 操作(应该使用具有不同参数 DoSomething("item_name") 的相同方法)。
How should I do this?
我该怎么做?
Thanks for your time. Best regards.
谢谢你的时间。此致。
采纳答案by itsmatt
So, you can clear the items from the context menu with:
因此,您可以使用以下命令从上下文菜单中清除项目:
myContextMenuStrip.Items.Clear();
You can add an item by calling:
您可以通过调用添加项目:
myContextMenuStrip.Items.Add(myString);
The context menu has an ItemClicked event. Your handler could look like so:
上下文菜单有一个 ItemClicked 事件。您的处理程序可能如下所示:
private void myContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
DoSomething(e.ClickedItem.Text);
}
Seems to work OK for me. Let me know if I misunderstood your question.
对我来说似乎工作正常。如果我误解了您的问题,请告诉我。
回答by tomloprod
Another alternative using a ToolStripMenuItem
object:
使用ToolStripMenuItem
对象的另一种选择:
//////////// Create a new "ToolStripMenuItem" object:
ToolStripMenuItem newMenuItem= new ToolStripMenuItem();
//////////// Set a name, for identification purposes:
newMenuItem.Name = "nameOfMenuItem";
//////////// Sets the text that will appear in the new context menu option:
newMenuItem.Text = "This is another option!";
//////////// Add this new item to your context menu:
myContextMenuStrip.Items.Add(newMenuItem);
Inside the ItemClicked
event of your myContextMenuStrip
, you can check which option has been chosen (based on the name property of the menu item)
在ItemClicked
您的事件中myContextMenuStrip
,您可以检查选择了哪个选项(基于菜单项的 name 属性)
private void myContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
ToolStripItem item = e.ClickedItem;
//////////// This will show "nameOfMenuItem":
MessageBox.Show(item.Name, "And the clicked option is...");
}