【问题标题】:TreeView HierarchicalDataTemplate does not apply ItemContainerStyleTreeView HierarchicalDataTemplate 不适用 ItemContainerStyle
【发布时间】:2015-08-24 08:32:46
【问题描述】:

我尝试使用 TreeView 显示分层数据,我想为我的不同儿童类型设置不同的 DataTemplates。

但问题是,我的风格没有得到应用。

也许这是一个非常简单的错误,但我真的没有找到它。

<TreeView ItemsSource="{Binding List}">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:Main}" ItemsSource="{Binding Children}">
            <TextBlock Text="{Binding Property1}"/>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="{x:Type local:Type2}">
            <HierarchicalDataTemplate.ItemContainerStyle>
                <Style TargetType="TreeViewItem">
                    <Setter Property="IsExpanded" Value="True"/>
                </Style>
            </HierarchicalDataTemplate.ItemContainerStyle>
            <TextBlock Text="{Binding Property2}"/>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="{x:Type local:Type3}">
            <HierarchicalDataTemplate.ItemContainerStyle>
                <Style TargetType="TreeViewItem">
                    <Setter Property="IsExpanded" Value="False"/>
                </Style>
            </HierarchicalDataTemplate.ItemContainerStyle>
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

【问题讨论】:

  • 首先想到 - TargetType 不应该是“{x:Type TreeViewItem}”
  • 第二个想法-“IsExpaned”中有错字-应该是“IsExpanded”-注意第二个D
  • 感谢您的回答,但两者都没有帮助。
  • 嗯,这是一个有趣的问题,我会进一步研究它。作为一种解决方法,您可以为该树中的所有 TreeViewItem 设置一个样式,将 IsExpanded 绑定到 VM 上的某个变量,然后将 Type3 设置为 false,Type2 设置为 true?这肯定会奏效,让你得到你想要的。它只是不使用 ItemContainerStyle 功能。

标签: wpf xaml treeview hierarchicaldatatemplate itemcontainerstyle


【解决方案1】:

好的,我知道出了什么问题。 HierarchicalDataTemplate.ItemContainerStyle 包含应用于 ItemsContainer 的样式,其中存储了当前节点的 children。试试这个作为一个实验,改变你的风格:

    <HierarchicalDataTemplate.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="IsExpanded" Value="True" />
            <Setter Property="Foreground" Value="Navy" />
        </Style>
    </HierarchicalDataTemplate.ItemContainerStyle>

您会注意到,您放置此样式的节点继续具有黑色前景,但它的所有 子节点 现在将具有海军蓝的前景。

这有点违反直觉,但是当您考虑它时,我想它是有道理的。因此,考虑到这一点,我认为最好的解决方案是将所有 TreeViewItems 的 IsExpanded 绑定到 VM 中的一个变量,然后根据那里的类型选择不同的值。

【讨论】:

    【解决方案2】:

    我可能有类似的问题。如果 Main、Type2 和 Type3 是 XAML 中的选择不起作用的接口,我必须使用类。如果你想使用接口,你可以实现一个模板选择器。

    【讨论】:

    • 感谢您的回答,但它们不是接口。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多