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

这可能非常简单,我没有看到它,因为这是漫长的一天的结束,如果是我提前道歉。 我有一组按钮,右键单击时会弹出一个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; 
我需要能够获得触发ContextMenu的Button在MenuItem的Click处理程序中弹出,或以某种方式获取它。 MenuItem.Click接受EventArgs,所以没有什么用处。我可以将对象发送者强制转换回MenuItem,但我找不到任何告诉我是什么让它弹出的东西。这可能吗?     
已邀请:
使用ContextMenu.SourceControl属性,它为您提供对Button实例的引用。     
在上面的代码摘录中,当您调用
buttonContextMenu
的show方法时,右键单击按钮时将按钮对象传递给
buttonContextMenu
。 要访问OnFooClicked方法中的按钮,只需将“发件人”转换回按钮即可。
public void OnFooClicked(object sender, EventArgs e)
{
     ((MenuItem)sender).Parent //This is the button
}
*我不知道MenuItem是否是正确的演员,但它应该沿着这些线。     
如果您使用的是ContextMenuStrip和ToolStripItem,而不是ContextMenu和MenuItem,则需要:
private void myToolStripMenuItem_Click(object sender, EventArgs e)
{
   Button parent = (Button)((ContextMenuStrip)((ToolStripItem)sender).Owner).SourceControl;
   ...
使用常规的ContextMenu和MenuItem(来自trycatch对Hans Passant帖子的评论):
Button parent = (Button)((ContextMenu)((MenuItem)sender).Parent).SourceControl; 
    

Button buttonThatTriggeredTheContextMenu; 

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


public void OnFooClicked(object sender, EventArgs e)
{
    //buttonThatTriggeredTheContextMenu contains the button you want
}

    
我不是百分之百 - 这是我2年前编写的代码,但我希望它能让你继续前进。
MenuItem item = (MenuItem)sender;
DependencyObject dep = item.Parent;
while((dep != null) && !(dep is Button))
    dep =  VisualTreeHelper.GetParent(dep);

if (dep == null)
    return;
Button button = dep as Button;
    
button mybutton = ((ContextMenu)((MenuItem)sender).Parent).SourceControl as button;
    

要回复问题请先登录注册