在代码中获取上下文菜单的所有者 [英] Get owner of context menu in code
本文介绍了在代码中获取上下文菜单的所有者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的 ContextMenu
:
<StackPanel Orientation="Horizontal">
<StackPanel.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete" Click="OnDeleteClicked" />
</ContextMenu>
</StackPanel.ContextMenu>
</StackPanel>
我需要获取 StackPanel $ c $的实例拥有
ContextMenu
的c>。我已经尝试过:
And I need to get the instance of the StackPanel
that owns that ContextMenu
. I already tried this:
private void OnDeleteClicked(object sender, System.Windows.RoutedEventArgs e)
{
FrameworkElement parent = e.OriginalSource as FrameworkElement;
while (!(parent is StackPanel))
{
parent = (FrameworkElement)LogicalTreeHelper.GetParent(parent);
}
}
但是在获取 ContextMenu之后
弹出父级,它为null,与 VisualTreeHelper
相同,在获取 StackPanel $ c之前为null。 $ c>。知道如何执行此操作吗?
But after getting the ContextMenu
Popup parent, it gets null, same with the VisualTreeHelper
, it gets to null before getting the StackPanel
. Any idea on how to do this?
谢谢!
推荐答案
这将为您提供所需的确切内容
this will give you the exact thing you want
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;
}
}
希望这会有所帮助!
这篇关于在代码中获取上下文菜单的所有者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文