【问题标题】:Bind to DataContext of TreeView from HierachicalDataTemplate从 HierachicalDataTemplate 绑定到 TreeView 的 DataContext
【发布时间】:2011-06-22 09:02:19
【问题描述】:

我有一个 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>

【问题讨论】:

    标签: wpf xaml data-binding hierarchicaldatatemplate relativesource


    【解决方案1】:

    您可以使用 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>
    

    【讨论】:

      猜你喜欢
      • 2019-01-21
      • 2018-08-29
      • 1970-01-01
      • 2014-07-30
      • 2013-02-04
      • 2010-12-03
      • 2013-07-25
      • 1970-01-01
      • 2013-02-02
      相关资源
      最近更新 更多