WPF上下文菜单绑定

时间:2012-08-29 07:23:02

标签: wpf contextmenu

似乎无法将我的contextmenu中的menuitem绑定到我的viewmodel中的命令。我知道contextmenu不在视觉树中。出于测试目的,我在一个按钮中绑定了两次相同的命令。第一个绑定工作但我可以在contextmenu中获得第二个绑定绑定。我可以在输出中看到绑定错误。有人有什么想法吗?

<HierarchicalDataTemplate DataType="{x:Type inf:OSiteEquipment}" ItemsSource="{Binding Path=SubSystems, Converter={StaticResource subsystemConverter}}"  >
                <Button HorizontalContentAlignment="Left"
                        Command="{Binding DataContext.CommandOpenSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"
                        CommandParameter="{Binding}">

                    <TextBlock Text="{Binding Path=PartData.Name}" TextTrimming="CharacterEllipsis" />
                    <Button.ContextMenu>
                        <ContextMenu>                                                                         

     <MenuItem Header="Add Category"  Command="{Binding Path=Parent.PlacementTarget.Tag.CommandOpenSelected, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
                        </ContextMenu>

                    </Button.ContextMenu>
                </Button>
            </HierarchicalDataTemplate>

2 个答案:

答案 0 :(得分:0)

只需删除数据绑定路径中的“Parent”:

<HierarchicalDataTemplate DataType="{x:Type inf:OSiteEquipment}" ItemsSource="{Binding Path=SubSystems, Converter={StaticResource subsystemConverter}}"  >
    <Button HorizontalContentAlignment="Left"
            Command="{Binding DataContext.CommandOpenSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"
            CommandParameter="{Binding}">

        <TextBlock Text="{Binding Path=PartData.Name}" TextTrimming="CharacterEllipsis" />
        <Button.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Add Category"  Command="{Binding Path=PlacementTarget.Command, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
            </ContextMenu>
        </Button.ContextMenu>
    </Button>
</HierarchicalDataTemplate>

答案 1 :(得分:0)

  1. 您已通过相关来源找到Parent - &gt;省略路径中的Parent
  2. 您甚至没有在TagPlacementTarget) - &gt;上设置Button。分别设置