WPF:如何从网格控件的所有区域打开上下文菜单
我正在尝试将 ContextMenu 添加到 WPF 中的 ListBox 中的项目;
<ListBox.ItemTemplate>
<DataTemplate>
<Border>
<Grid>
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header = "Menu item 1"/>
<MenuItem Header = "Menu item 2"/>
<MenuItem Header = "Menu item 3"/>
</ContextMenu>
</Grid.ContextMenu>
........
........
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
问题是上下文菜单仅在单击网格的实际上下文时才会打开,我希望能够通过单击列表框项上的任意位置来打开菜单。
我应该将网格包装在其他控件中吗?
I'm trying to add a ContextMenu to items in a ListBox in WPF;
<ListBox.ItemTemplate>
<DataTemplate>
<Border>
<Grid>
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header = "Menu item 1"/>
<MenuItem Header = "Menu item 2"/>
<MenuItem Header = "Menu item 3"/>
</ContextMenu>
</Grid.ContextMenu>
........
........
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
The problem is that the ContextMenu will only open when clicking on the actual context of the Grid, I want to be able to open the menu by clicking anywhere on the Listbox item.
Should I wrap the Grid in some other control?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我已经有几个月没有完成任何可靠的 WPF 开发了(从应用程序开发转移到实际的游戏团队)。
根据记忆,您需要设置
Border
上的ContextMenu
属性,然后设置Border.Background=Transparent
。将背景设置为透明可确保其参与命中检测。替代解决方案是确保 Grid 元素水平和垂直拉伸以适合容器。
...
还将
ContextMenu
作为静态资源拉出,以便将来更容易查找/编辑。希望这会有所帮助(我的记忆力不会让我失望)。
编辑:我之前在 StackOverflow 上回答过类似的问题,请参阅我在 WPF:显示 GridView 项目的上下文菜单。这个答案更完整,因为它将焦点设置在
ListItem
上。It has been a several months since I've done any solid WPF development (was moved from application development to an actual game team).
From memory, you want to set the
ContextMenu
property on theBorder
and then set theBorder.Background=Transparent
. Setting the background to transparent ensures that it will be participate in the hit detection.Alternative solution, would be ensure you
Grid
element stretches horizontally and vertically to fit the container....
Also pull the
ContextMenu
out as a static resource, so that is will be easier to find/edit in the future.Hope this helps (and my memory does not fail me).
EDIT: I have answered a similar question on StackOverflow previously, please see my answer on WPF: Displaying a Context Menu for a GridView's Items. This answer is more complete as it sets the focus on the
ListItem
.正如您已经意识到的那样,感谢丹尼斯,您必须设置一些背景。是的,透明背景也可以:
参考:https://blogs.msdn.microsoft.com/domgreen/2008/12/08/wpf-hit-testing-with-event-bubbling/
As you have already realized, - thanks to Dennis, - you have to set some background. Yes, transparent background is also OK:
REFERENCE: https://blogs.msdn.microsoft.com/domgreen/2008/12/08/wpf-hit-testing-with-event-bubbling/