2016-09-26 14 views
2

私は階層データテンプレートを持つツリービューを持っており、ContextMenuのDataContextを設定しようとしています。私は研究を行い、ContextMenuがその親のDataContextを継承しないことを知っています。私はこれらの投稿に従いました:How to set the RelativeSource in a DataTemplate that is nested in a HierarchicalDataTemplate?階層データテンプレートを使用したツリービューでのcontextmenuコマンドのバインド

How to bind to the DataContext of a HierarchicalDataTemplate from its ItemTemplate XAML?まだ動作させることはできません。どんな助けもありがとう。ここに私のサンプルコードは次のとおりです。それを解決するために

<TreeView.Resources> 
    <HierarchicalDataTemplate DataType="{x:Type viewModels:SiteViewModel}" ItemsSource="{Binding Children}"> 
     <StackPanel Orientation="Horizontal"> 
      <StackPanel.Resources> 
      </StackPanel.Resources> 
      <Image Width="16" Height="16" Margin="3,0" /> 
      <TextBlock Text="{Binding SiteName}" /> 
     </StackPanel> 
    </HierarchicalDataTemplate> 


    <HierarchicalDataTemplate DataType="{x:Type viewModels:LevelViewModel}" ItemsSource="{Binding Children}" > 
     <StackPanel Orientation="Horizontal" > 
      <Image Width="16" Height="16" Margin="3,0" /> 
      <TextBlock Text="{Binding LevelName}" > 
       <TextBlock.ContextMenu > 
       <ContextMenu> 
        <MenuItem Header="Test" Command="{Binding ?????????" CommandParameter="{Binding}"/> 
       </ContextMenu> 
       </TextBlock.ContextMenu> 
      </TextBlock> 
     </StackPanel> 
    </HierarchicalDataTemplate> 

答えて

0

一つの方法: 私の場合、私はそのようなものを持っていた:

<DataTemplate DataType="..."> 
       <TreeView> 
        <TreeViewItem Tag="{Binding ElementName=LocalControl, Path=DataContext}" 
            Header="{Binding ...}" 
            ContextMenu="{StaticResource ...}"> 
         ... 
        </TreeViewItem> 
       </TreeView> 
</DataTemplate> 

あなたは、そののDataContextに親ツリービューアイテムのタグ属性をバインドする必要があり、その後、コンテキストメニューの階層テンプレートのどこかに、親コントロールのTagにDataContextをバインドする必要があります。

<ContextMenu x:Key="CyclogramFolderContextMenu" 
         DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}"> 
       <TextBlock Text="Do something" > 
        <TextBlock.InputBindings> 
         <MouseBinding Command="{Binding Path=(viewModels:someViewModel.SomeCommand)}" MouseAction="LeftClick" /> 
        </TextBlock.InputBindings> 
       </TextBlock> 
</ContextMenu> 
関連する問題