如何在.Net中的ContextMenuStrip中返回子菜单内的ToolStripMenuItem的名称

| 我的问题可能不明确,但这是我的情况: 我的窗体上有一个方形的图片框阵列,每个图片框都有一个处理程序来打开ContextMenuStrip,其内容是基于目录生成的。目录中的每个文件夹将创建一个ToolStripMenuItem,并且该文件夹中的每个文件将在所述菜单菜单项的DropDownItems内部表示。单击菜单的子项后,图片框的图像将根据单击的菜单项而变化。 当我尝试找出单击了哪个子项时出现了我的问题。我如何通过ContextMenuStrip的_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:\");
    }
}
    

要回复问题请先登录注册