我有一个每5秒重新生成一次的字符串列表。我想创建一个上下文菜单,并使用此列表动态设置它的项目。 问题是,我甚至不知道如何做到这一点,并为每个生成的项目(应该使用与不同参数DoSomething(“item_name”))相同的方法来管理Click动作。将项目动态添加到上下文菜单并设置点击操作
我该怎么做?
谢谢你的时间。 此致敬礼。
我有一个每5秒重新生成一次的字符串列表。我想创建一个上下文菜单,并使用此列表动态设置它的项目。 问题是,我甚至不知道如何做到这一点,并为每个生成的项目(应该使用与不同参数DoSomething(“item_name”))相同的方法来管理Click动作。将项目动态添加到上下文菜单并设置点击操作
我该怎么做?
谢谢你的时间。 此致敬礼。
所以,你可以清除从上下文菜单中的项目有:
myContextMenuStrip.Items.Clear();
你可以通过调用添加项目:
myContextMenuStrip.Items.Add(myString);
上下文菜单中有一个ItemClicked事件。您的处理程序可能看起来像这样:
private void myContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
DoSomething(e.ClickedItem.Text);
}
似乎工作对我来说OK。如果我误解了你的问题,请告诉我。
使用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);
里面的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...");
}
谢谢!这就是我正在寻找的 – 2008-10-22 12:28:53