在代码中获取上下文菜单的所有者

时间:2009-12-10 21:21:15

标签: wpf contextmenu parent

我有ContextMenu这样:

<StackPanel Orientation="Horizontal">
    <StackPanel.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Delete" Click="OnDeleteClicked" />
        </ContextMenu>
    </StackPanel.ContextMenu>
</StackPanel>

我需要获取拥有该StackPanel的{​​{1}}的实例。我已经尝试过了:

ContextMenu

但是在获得private void OnDeleteClicked(object sender, System.Windows.RoutedEventArgs e) { FrameworkElement parent = e.OriginalSource as FrameworkElement; while (!(parent is StackPanel)) { parent = (FrameworkElement)LogicalTreeHelper.GetParent(parent); } } Popup父级后,它变为null,与ContextMenu相同,在获得VisualTreeHelper之前变为null。关于如何做到这一点的任何想法?

谢谢!

3 个答案:

答案 0 :(得分:52)

这将为您提供您想要的确切内容

private void OnDeleteClicked(object sender, System.Windows.RoutedEventArgs e)
{
    MenuItem mnu = sender as MenuItem;
    StackPanel sp = null;
    if(mnu!=null)
    {
        sp = ((ContextMenu)mnu.Parent).PlacementTarget as StackPanel;
    }
}

希望这会有所帮助!!

答案 1 :(得分:6)

ContextMenus和Popups的可视化树的工作方式略有不同。您可以使用ContextMenu.PlacementTarget来获取StackPanel。 MSDN上提供了更多信息:http://msdn.microsoft.com/en-us/library/system.windows.controls.contextmenu.placementtarget.aspx

答案 2 :(得分:1)

上下文菜单有自己的可视化树,尝试从事件处理程序中调用它,如下所示: -

StackPanel stackPanel = GetStackPanelItemFromContextMenu((FrameworkElement)sender, yourStackPanel);

  private StackPanel GetStackPanelItemFromContextMenu(FrameworkElement sender, StackPanel stackPanel) {
     Point menuClickPoint = ((sender as FrameworkElement).Parent as ContextMenu).TranslatePoint(new Point(0, 0), stackPanel);

     // get the first potential object that was hit   
     DependencyObject obj = stackPanel.InputHitTest(menuClickPoint) as DependencyObject;

     // cycle up the tree until you hit the StackPanel
     while (obj != null && !(obj is StackPanel)) {
        obj = VisualTreeHelper.GetParent(obj);
     }

     return obj as StackPanel;
  }