wpf – 从HierachicalDataTemplate绑定到TreeView的DataContext

我有一个TreeView,其中包含由HierarchicalDataTemplate填充的项目.我试图从HierarchicalDataTemplate内部获取TreeView的DataContext中的属性.有人可以帮忙吗?这是我在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>

最佳答案 您可以使用TextBlock的Tag来引用TreeView的DataContext,然后您可以通过PlacementTarget使用相对源绑定在ContextMenu中获取它,例如:

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

如果要保留上下文菜单的原始DataContext,可以使用完整路径绑定直接导航到属性,例如:

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