Here's an answer I came up with. I don't really like it because it's a bit hack-ish, but it works. The idea is that you make your labels listen to the MouseRightButtonUp
event, which is fired when the user releases the right mouse button after clicking to open the context menu. In the event handler, you set a private Label variable to the label that the user just right-clicked. Then, in your MenuItem click handler, you can access that private Label variable. Note that all the labels you want to do this must use the same event handler for MouseRightButtonUp.
For example:
<Window.Resources>
<ContextMenu x:Key="MyMenu">
<MenuItem Header="Edit" Click="Edit_Click"/>
<MenuItem Header="Clear" Click="Clear_Click"/>
</ContextMenu>
</Window.Resources>
<StackPanel>
<Label ContextMenu="{StaticResource MyMenu}"
MouseRightButtonUp="Label_MouseRightButtonUp">Some text</Label>
<Label ContextMenu="{StaticResource MyMenu}"
MouseRightButtonUp="Label_MouseRightButtonUp">Some junk</Label>
<Label ContextMenu="{StaticResource MyMenu}"
MouseRightButtonUp="Label_MouseRightButtonUp">Some stuff</Label>
<Label ContextMenu="{StaticResource MyMenu}"
MouseRightButtonUp="Label_MouseRightButtonUp">Some 0000</Label>
</StackPanel>
Code behind:
private void Edit_Click(object sender, RoutedEventArgs e)
{
if (clickedLabel != null)
{
MessageBox.Show(clickedLabel.Content.ToString());
}
}
private void Clear_Click(object sender, RoutedEventArgs e)
{
if (clickedLabel != null)
{
MessageBox.Show(clickedLabel.Content.ToString());
}
}
private Label clickedLabel;
private void Label_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
clickedLabel = (Label)sender;
}