C#WPF上下文菜单项单击事件返回null [英] C# WPF Context menu item click event returns null
问题描述
我正在使用WPF和C#。我有一个按钮网格,并且为每个按钮(如果右键单击)分配了一个上下文菜单。右键单击按钮可以正常工作,并显示上下文菜单,但是单击菜单项将为空发送者。有什么事吗以下是嵌入到Windows XAML代码中的相关代码:
I'm using WPF with C#. I have a grid of buttons and I've assigned a context menu to each button if it's right-clicked. Right-clicking the buttons works fine and the context menu shows up but clicking the menu items gives a null sender. What could be wrong? Here is the relevant code embedded into the Window XAML code:
<Window.Resources>
<ContextMenu x:Key="cmButton">
<MenuItem Header="Copy" Click="Copy_Click" />
<MenuItem Header="Cut" />
<Separator />
<MenuItem Header="Paste" Click="Paste_Click" />
</ContextMenu>
</Window.Resources>
这是相关的C#代码:
public void WarpHeadCell_RightClick(DraftWindow w, Button b)
{
ContextMenu cm = w.FindResource("cmButton") as ContextMenu;
cm.PlacementTarget = b;
cm.IsOpen = true;
}
private void Copy_Click(object sender, RoutedEventArgs e)
{
MenuItem mi = e.OriginalSource as System.Windows.Controls.MenuItem;
ContextMenu cm = mi.ContextMenu;
Button b = (Button)cm.PlacementTarget;
}
mi始终为null,有人知道吗?
mi is always null, does anybody have a clue?
推荐答案
我看不出mi会为null的任何原因,但是您还没有包含所有内容,所以我走到这里,猜测mi.ContextMenu是您遇到问题的地方。菜单项本身没有ContextMenu,但确实具有Parent属性,它是它所属的ContextMenu,可能正是您要查找的内容。
I don't see any reason why mi would be null, but you haven't included everything, so I'm going out on a limb here and guessing that mi.ContextMenu is where you are running into a problem. The menu item itself doesn't have a ContextMenu, but it does have a Parent property, which is the ContextMenu it belongs to and is probably what you are looking for.
private void Copy_Click(object sender, RoutedEventArgs e)
{
MenuItem mi = sender as MenuItem;
ContextMenu cm = mi.Parent as ContextMenu;
Button b = cm.PlacementTarget as Button;
}
这篇关于C#WPF上下文菜单项单击事件返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!