C#= MenuItem.Click handler - 获取上下文菜单所属的对象?

try*_*tch 3 c# events contextmenu winforms

这可能非常简单,我没有看到它,因为这是漫长的一天的结束,如果它是我提前道歉.

我有一组按钮,右键单击时会弹出一个ContextMenu.该菜单有两个MenuItem,它们都分配了一个Click处理函数.我正在触发ContextMenu弹出右键单击按钮,如下所示:

过于简化的例子:


public void InitiailizeButtonContextMenu()
{
    buttonContextMenu = new ContextMenu();
    MenuItem foo = new MenuItem("foo");
    foo.Click += OnFooClicked;

    MenuItemCollection collection = new MenuItemCollection(buttonContextMenu);
    collection.Add(foo);
}

public void OnButtonMouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
        // left click stuff handling
    if (e.Button == MouseButtons.Right)
        buttonContextMenu.Show((Button)sender, new Point(e.X, e.Y));
}


public void OnFooClicked(object sender, EventArgs e)
{
    // Need to get the Button the ContextMenu .Show'd on in
    // OnButtonMouseClick...  thoughts?
}


ContextMenu buttonContextMenu; 
Run Code Online (Sandbox Code Playgroud)

我需要能够获得触发ContextMenu的Button在MenuItem的Click处理程序中弹出,或以某种方式获取它.MenuItem.Click接受EventArgs,所以没有什么用处.我可以将对象发送者强制转换回MenuItem,但我找不到任何告诉我是什么让它弹出的东西.这可能吗?

Han*_*ant 7

使用ContextMenu.SourceControl属性,它为您提供对Button实例的引用.

  • 值得注意的是(如果遇到同样问题的人遇到这个问题)你必须这样做:Button parent =(Button)((ContextMenu)((MenuItem)sender).Parent).SourceControl; 从MenuItem一直回到按钮,但这是有效的!谢谢. (3认同)