Getting the control of a context menu

左心房为你撑大大i 提交于 2019-12-12 09:55:02

问题


I have a context menu that looks like this

 A
 |--1
 |--2
 |--3

I need to access the object that the context menu is called from, after selecting 1 2 or 3

meaning if this is a context menu of a textbox1 then I need to access that object, how do I do that?

Forgot to mention, this is a WPF application. so Im using the System.Windows.Controls and the ContextMenu is created programmatically


回答1:


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;
        //...
    }
}



回答2:


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;



回答3:


use the

ContextMenu.SourceControl

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




回答4:


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)




回答5:


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.




回答6:


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; 
}


来源:https://stackoverflow.com/questions/6720366/getting-the-control-of-a-context-menu

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