如何返回ToolStripMenuItem的名称在子菜单中的上下文菜单
本文关键字:菜单 何返回 上下文 返回 ToolStripMenuItem | 更新日期: 2023-09-27 17:50:20
我的问题可能是模棱两可的,但这是我的情况:
我的表单上有一个方形的图片框数组,每个都有一个处理程序来打开上下文菜单条,其内容是基于目录生成的。目录中的每个文件夹将创建一个ToolStripMenuItem,该文件夹中的每个文件将在上述菜单项的DropDownItems中表示。当点击我的菜单的子项时,图片框的图像将根据点击的菜单项而改变。
当我试图找出哪个子项被单击时,问题出现了。我怎么能找到与上下文菜单条的_Clicked事件?以下是我到目前为止的尝试:
private void mstChooseTile_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
ContextMenuStrip s = (ContextMenuStrip)sender;
ToolStripMenuItem x = (ToolStripMenuItem)e.ClickedItem;
// Test to see if I can get the name
MessageBox.Show(x.DropDownItems[1].Name);
// Nope :(
}
ItemClicked
事件不适合您:
A)只对直系子女有效。
B)即使点击非叶节点也会触发。
尝试订阅每个ToolStripMenuItem。这里我跳过订阅非叶节点。
using System;
using System.Windows.Forms;
public class Form1 : Form
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
public Form1()
{
ContextMenuStrip = new ContextMenuStrip
{
Items =
{
new ToolStripMenuItem
{
Text = "One",
DropDownItems =
{
new ToolStripMenuItem { Text = "One.1" },
new ToolStripMenuItem { Text = "One.2" },
new ToolStripMenuItem { Text = "One.3" },
new ToolStripMenuItem { Text = "One.4" },
},
},
new ToolStripMenuItem
{
Text = "Two",
},
new ToolStripMenuItem
{
Text = "Three",
DropDownItems =
{
new ToolStripMenuItem { Text = "Three.1" },
new ToolStripMenuItem { Text = "Three.2" },
},
},
}
};
foreach (ToolStripMenuItem item in ContextMenuStrip.Items)
Subscribe(item, ContextMenu_Click);
}
private static void Subscribe(ToolStripMenuItem item, EventHandler eventHandler)
{
// If leaf, add click handler
if (item.DropDownItems.Count == 0)
item.Click += eventHandler;
// Otherwise recursively subscribe
else foreach (ToolStripMenuItem subItem in item.DropDownItems)
Subscribe(subItem, eventHandler);
}
void ContextMenu_Click(object sender, EventArgs e)
{
MessageBox.Show((sender as ToolStripMenuItem).Text, "The button clicked is:");
}
}