首页 > 其他 > 详细

WPF中ContextMenu通过CommandParameter传参

时间:2014-02-21 06:32:20      阅读:406      评论:0      收藏:0      [点我收藏+]

场景:ListBox中有个ContextMenu,希望点击其中一个菜单项的时候把ListBox当做CommandParameter传递给Command,但是发现无论是通过ElementName还是RelativeSource中的FindAncestor传值,命令接收到的参数一直都是null。

分析:通过网上查找,找到这么一句话“The problem is that the ContextMenu is at the root of its own visual tree, so any RelativeSource.FindAncestor bindings won‘t go past the ContextMenu.”原来原因在这里,ContextMenu是它自身视觉树的根节点,所以通过RelativeSource.FindAncestor就找不到ListBox。另:ContextMenu有其自身的视觉树并且它不是ListBox视觉树的一部分。

解决:可以通过PlacementTarget解决。微软对PlacementTarget的解释是:获取或设置UIElement,当它打开时相对于它确定ContextMenu的位置。应该可以理解为放置此ContextMenu的UIElement。

那么我们这么做就行了:

CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}, Path=PlacementTarget}"

如果要传递ListBox的SelectedItem的话可以用:

CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}"

WPF中ContextMenu通过CommandParameter传参

原文:http://blog.csdn.net/jumtre/article/details/19540371

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!