Silverlight Toolkit ContextMenu: Which control was

2019-05-30 06:41发布

问题:

The Silverlight Toolkit has a lovely ContextMenu, which can be shared among multiple instances of controls such as Textbox. Sharing can result from the ContextMenu being declared in a container which also hosts other controls.

<StackPanel>
    <TextBox x:Name="box1" Text="{Binding str1}"  />
    <TextBox x:Name="box2" Text="{Binding str2}"  />
    <toolkit:ContextMenuService.ContextMenu>
        <toolkit:ContextMenu Name="cm">
            <toolkit:MenuItem Name="cmiCut" Header="Cut" />
            <toolkit:MenuItem Name="cmiCopy" Header="Copy" />
            <toolkit:Separator/>
            <toolkit:MenuItem Name="cmiPaste" Header="Paste" />
        </toolkit:ContextMenu>
    </toolkit:ContextMenuService.ContextMenu>
</StackPanel>

Sharing can also be achieved with a call to ContextMenuService.SetContextMenu.

When the ContextMenu is shared, it's very helpful for the eventhandler to know which control was right-clicked to open the ContextMenu (e.g. context). Could anyone offer an efficient way to do this?

For comparison, this need is addressed in other platforms as follows:

  1. WPF's ContextMenu has ContextMenu.PlacementTarget
  2. WinForms' ContextMenuStrip has ToolStripItem.Owner.SourceControl

Thanks,

Bill

回答1:

I'd like to thank Erik Noren for blogging on this topic. I defined my ContextMenu in a Rectangle with Visibility=Collapsed on my MainPage.xaml so that it doesn't handle the mouse right click event. When the right mouse button is clicked anywhere on the page, I use

VisualTreeHelper.FindElementsInHostCoordinates

to identify a Textbox at the click position and then open the ContextMenu. Erik's technique for finding a control with SelectedText dependency property is brilliant.