I have a context menu that is divided into 6 different labels, how can I determine which label uses the current instance of the context menu?

Here is the xaml for contextMenu:

    <Window.Resources>
    <ContextMenu x:Key="IBContextMenu" x:Shared="true" Name="IBContextMenu1">
        <MenuItem Header="Edit" Click="ibEdit_Click" AllowDrop="False" />
        <MenuItem Header="Clear" Click="ibClear_Click"/>
    </ContextMenu>
</Window.Resources>

Both editing methods and clear elements need to know which label to act on. How can i do this?

+3
source share
3 answers

I think you're looking for PlacementTarget: http://msdn.microsoft.com/en-us/library/system.windows.controls.contextmenu.placementtarget.aspx

If you go to the Command template, you can get it through Binding and pass it as CommandParameter ...

+4
source

, . , -, . , MouseRightButtonUp, , , . Private Label , . MenuItem Label. , , , MouseRightButtonUp.

:

<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>

:

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;
}
+1

DataContext ,

And in the Click event, just check the sender ((FrameworkElement)). DataContext for FIRST / SECOND etc. Let us know if this works.

0
source

Source: https://habr.com/ru/post/1732438/


All Articles