Reputation: 175
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>
And here is the relevant C# code:
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?
Upvotes: 1
Views: 2485
Reputation: 101
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;
}
Upvotes: 4
Reputation: 397
This is my 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
Upvotes: 2