Bind to DataContext TreeView from HierachicalDataTemplate

I have a TreeView that contains items filled with a HierarchicalDataTemplate. I am trying to get to a property in a TreeView DataContext from a HierarchicalDataTemplate. Can anyone help? Here is what I tried in the HierarchicalDataTemplate:

<HierarchicalDataTemplate x:Key="MyTopLevel" ItemTemplate="{StaticResource LowerLevelTemplate}" ItemsSource="{Binding LowerLevel}"> <TextBlock Text="{Binding Name, Mode=OneWay}" ToolTip="{Binding Name, Mode=OneWay}"> <TextBlock.ContextMenu> <ContextMenu x:Name="MyContextMenu"> <MenuItem Header="{Binding DataContext.Test, RelativeSource={RelativeSource AncestorType={x:Type TreeView}}}" /> </ContextMenu> </TextBlock.ContextMenu> </TextBlock> </HierarchicalDataTemplate> 
+4
source share
1 answer

You can use the TextBlock tag to refer to the DataContext TreeView, then you can get it inside ContextMenu using relative source binding via PlacementTarget , for example:

 <TextBlock Text="{Binding Name, Mode=OneWay}" Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=TreeView}}"> <TextBlock.ContextMenu> <ContextMenu DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}"> <MenuItem Header="{Binding Test}"/> </ContextMenu> </TextBlock.ContextMenu> </TextBlock> 

If you want to keep the original DataContext of the context menu, you can directly go to the properties using full path binding, for example:

 <TextBlock Text="{Binding Name, Mode=OneWay}" Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=TreeView}}"> <TextBlock.ContextMenu> <ContextMenu> <MenuItem Header="{Binding PlacementTarget.Tag.Test, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/> </ContextMenu> </TextBlock.ContextMenu> </TextBlock> 
+2
source

All Articles