Getting the control of a context menu

让人想犯罪 __ 提交于 2019-12-06 01:01:00

You can walk up the tree and get the control from the ContextMenu.PlacementTarget, e.g.

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    var item = sender as MenuItem;
    while (item.Parent is MenuItem)
    {
        item = (MenuItem)item.Parent;
    }
    var menu = item.Parent as ContextMenu;
    if (menu != null)
    {
        var droidsYouAreLookingFor = menu.PlacementTarget as TextBox;
        //...
    }
}

You can look at the SourceControl property of the ContextMenuStrip that owns the context menu item that was clicked.

For example, in the Click handler for the menu item:

private void aToolStripMenuItem_Click(object sender, EventArgs e)
{
    var control = ((sender as ToolStripMenuItem).Owner as ContextMenuStrip).SourceControl;
       ...
}

Of course if you only have one ContextMenuStrip on the form, you can just reference it directly

var control = myContextMenuStrip.SourceControl;

use the

ContextMenu.SourceControl

that's the variable that calls the context menu. all you need to do is cast the control

Bg1987

found the answer from a similar question

Get owner of context menu in code viky's code works, but I had to cast it twice.

I guess looping the casting of the Parent is possible for better flexibility (more casts depends on how deep the clicked item is)

Ugly Solution

I am searching for a better way to do the same thing. For now, the code below works:

TextBlock tb = ((sender as MenuItem).Parent as ContextMenu).PlacementTarget as TextBlock;

Replace TextBlock with your control's type.

Slight tweak to HB's answer. HB deserves the credit. Helped me find a DataGrid.

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    MenuItem item = sender as MenuItem;
    ContextMenu cm = (ContextMenu)item.Parent; 
    Popup popup = (Popup)cm.Parent; 

    var finalGoal = popup.PlacementTarget as DataGrid; 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!