WPF中ContextMenu通过CommandParameter传参

场景: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}"

 

更多

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

posted on 2014-07-08 18:04  大木哥  阅读(531)  评论(0编辑  收藏  举报

导航