Silverlight Toolkit ContextMenu: Which control was right-clicked?

限于喜欢 提交于 2019-12-08 08:12:26

问题


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.



来源:https://stackoverflow.com/questions/7909885/silverlight-toolkit-contextmenu-which-control-was-right-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!