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:
- WPF's ContextMenu has ContextMenu.PlacementTarget
- WinForms' ContextMenuStrip has ToolStripItem.Owner.SourceControl
Thanks,
Bill
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.
来源:https://stackoverflow.com/questions/7909885/silverlight-toolkit-contextmenu-which-control-was-right-clicked