我有一个场景,我有一个WPF TreeView控件,其中包含一个HierarchicalDataTemplate项目.现在里面的HierarchicalDataTemplate,我有一个Label和Label具有ContextMenu与一个菜单项Delete.菜单项被绑定到一个叫做命令删除DeleteCommand这是已被设置为一个类的一部分DataType的HierarchicalDataTemplate.
现在,我想在ContextMenu的menuitem中传递TreeView控件,这样我就可以在删除当前所选项目时处理TreeViewItems的选择.CommandParametersDeleteDeleteCommand
但是如果我将CommandParametersas {Binding ElementName=TreeViewName}或者其他任何东西绑定在一起,它总是为null,除非binded元素是一个属性DataContext.
任何人都可以帮助我解决方案,因为我认为,我已经尝试了所有可能的东西,如RelativeSource和AncestorType等,但它总是为空.对我来说,它看起来像是框架中的限制或错误.
Rob*_*nee 18
问题是ContextMenu是它自己的可视树的根,所以任何RelativeSource.FindAncestor绑定都不会超过ContextMenu.
一种解决方案是使用PlacementTarget属性从Label设置两阶段绑定:
<Label Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={
    x:Type TreeView}}}">
    <Label.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Delete" Command="{x:Static local:Commands.DeleteCommand}"
                CommandParameter="{Binding PlacementTarget.Tag, RelativeSource={
                RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"/>
        </ContextMenu>
    </Label.ContextMenu>
</Label>
然而,这非常hacky.最好将MenuItem 的CommandTarget属性设置为ContextMenu的PlacementTarget并在TreeView上设置命令处理程序.这意味着您不必通过TreeView.