开发者

Getting the control of a context menu

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开发者_如何学JAVA, 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


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;


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


use the

ContextMenu.SourceControl

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜