2012-08-29 167 views
1

似乎不能将我的contextmenu中的menuitem绑定到我的viewmodel中的命令。我知道contextmenu并不生活在视觉树中。出于测试目的,我已经在按钮中绑定了相同的命令两次。第一个绑定工作,但我可以在contextmenu中绑定第二个绑定。我可以看到输出中的绑定错误。有人有任何想法?WPF 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> 
+0

你能给出绑定错误吗? – mathieu

+0

System.Windows.Data错误:4:找不到与参考'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.ItemsControl',AncestorLevel ='1'绑定的源。 BindingExpression:路径= VerticalContentAlignment;的DataItem = NULL;目标元素是'TreeViewItem'(Name ='');目标属性是'VerticalContentAlignment'(类型'VerticalAlignment') – klashagelqvist

回答

0

只是删除了“家长”在数据绑定路径:

<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> 
+0

对不起,同样的问题。按钮的作品,contexmenu没有。 – klashagelqvist

+0

并显示相同的错误信息? – mathieu

+0

是的,完全一样 – klashagelqvist

0
  1. 你已经通过相对源找到Parent - >省略了Parent路径
  2. 你没有甚至在PlacementTarget上设置TagButton) - >分别设置