[英]C# WPF Context menu item click event returns null
I'm using WPF with C#. 我在C#中使用WPF。 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 XAML代码中的相关代码:
<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>
And here is the relevant C# code: 这是相关的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 is always null, does anybody have a clue? mi始终为空,有人知道吗?
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. 我看不出mi为何会为null的任何原因,但是您还没有包含所有内容,因此我在这里一头雾水,猜测mi.ContextMenu是您遇到问题的地方。 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. 菜单项本身没有ContextMenu,但确实具有Parent属性,这是它所属的ContextMenu,可能正是您要查找的内容。
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;
}
This is my XAML: 这是我的XAML:
<Window.Resources>
<ContextMenu x:Key="cmButton">
<MenuItem Click="Copy_Click" Header="Copy" />
<MenuItem Header="Cut" />
<Separator />
<MenuItem Click="Paste_Click" Header="Paste" />
</ContextMenu>
</Window.Resources>
<Grid>
<Button Content="SS" ContextMenu="{StaticResource cmButton}" />
</Grid>
This is my code: 这是我的代码:
private void Paste_Click(object sender, RoutedEventArgs e)
{
if (sender is MenuItem menuItem)
{
Debug.WriteLine("Ok");
}
if (e.OriginalSource is MenuItem menuItem2)
{
Debug.WriteLine("Ok");
}
}
It works, menuItem and menuItem2 is not null You can download my rar here: https://1drv.ms/u/s!AthRwq2eHeRWiOkw6MHXelG-ntjaDQ 它有效,menuItem和menuItem2不为空您可以在此处下载我的rar: https ://1drv.ms/u/s!AthRwq2eHeRWiOkw6MHXelG-ntjaDQ
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.