0

我的问题可能模棱两可,但这是我的情况:

我的表单上有一个方形数组,每个都有一个处理程序来打开 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 :(
    }
4

1 回答 1

4

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:");
    }
}
于 2011-04-17T21:15:21.343 回答