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 に答える