开发者

I have a context menu which is being shared by 6 different labels, how can I tell which label is using the current instance of the context menu?

Her开发者_运维知识库e is the xaml for the 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 the edit and clear items' methods need to know which label to act upon. How can I do this?


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

If you switch over to a Command-pattern, you can actually get this via Binding and pass it along as the CommandParameter...


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


Try to set a DataContext to the Labels, for example

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜