2
votes

I have a treeview with hierarchical data template and I am trying to set DataContext for ContextMenu, so I could bind commands to it. I have done research and know that ContextMenu doesn't inherit DataContext of its parent. I tried to follow these posts: How to set the RelativeSource in a DataTemplate that is nested in a HierarchicalDataTemplate?

How to bind to the DataContext of a HierarchicalDataTemplate from its ItemTemplate XAML? but still can't get it to work. Any help would be appreciated. Here is my sample code:

<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>
1

1 Answers

0
votes

One way to solve it: In my case I had something like that:

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

You need to bind Tag attribute of parent TreeViewItem to its DataContext, then somewhere in your hierarchical templates for context menu you should bind its DataContext to Tag of parent control:

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