zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    模拟乒乓球双打和单打比赛
    关于zip内置函数的应用及在 Python 2 和 3 的不同之处
    计算文本平均列数
    四则运算
    Python跳一跳小游戏
    数据库
    类和正则表达
    带进度条的圆周率计算
    球队预测
    自己的第一个网页
  • 原文地址:https://www.cnblogs.com/SimonGao/p/3832017.html
Copyright © 2011-2022 走看看