2012-08-29 207 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) - >分別設置