Silverlight工具包ContextMenu:右键单击哪个控件? [英] Silverlight Toolkit ContextMenu: Which control was right-clicked?
问题描述
Silverlight工具包具有一个漂亮的ContextMenu,可以在多个控件实例之间共享,例如Textbox。共享可能是由于在容器中声明了ContextMenu,该容器还承载其他控件。
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>
也可以通过调用ContextMenuService.SetContextMenu来实现共享。
Sharing can also be achieved with a call to ContextMenuService.SetContextMenu.
当共享ContextMenu时,事件处理程序知道右键单击哪个控件以打开ContextMenu(例如,上下文)非常有帮助。有人可以提供一种有效的方法来做到这一点吗?
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的ContextMenu具有ContextMenu.PlacementTarget
- WinForms的ContextMenuStrip具有ToolStripItem.Owner.SourceControl
谢谢
条例草案
推荐答案
我想感谢Erik Noren 博客一个>关于这个话题。我在MainPage.xaml上的Visibility = Collapsed中定义了矩形的ContextMenu,以便它不处理鼠标右键事件。在页面上的任何位置单击鼠标右键时,我都会使用
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
在单击位置标识一个文本框,然后打开ContextMenu。 Erik的具有SelectedText依赖项属性的控件的查找技巧非常出色。
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.
这篇关于Silverlight工具包ContextMenu:右键单击哪个控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!