【问题标题】:TreeView child nodes expand but root node does notTreeView 子节点展开但根节点不展开
【发布时间】:2012-03-31 12:00:13
【问题描述】:

我有一个奇怪的 WPF/XAML 问题。默认情况下,我希望扩展此 TreeView 中的所有节点。最终我会将它绑定到我的视图模型,但现在我只希望它们都默认展开。

这是有问题的代码部分(我目前正在使用)

<HierarchicalDataTemplate DataType="{x:Type Model:DirectoryItem}"
                          ItemsSource="{Binding Items}">
    <TextBlock Text="{Binding Path=Name}"
               ToolTip="{Binding Path=Path}" />
    <HierarchicalDataTemplate.ItemContainerStyle>   
        <Style TargetType="TreeViewItem">
            <Setter Property="IsExpanded" Value="True" />
        </Style> 
    </HierarchicalDataTemplate.ItemContainerStyle>
</HierarchicalDataTemplate>

<DataTemplate DataType="{x:Type Model:FileItem}">
    <TextBlock Text="{Binding Path=Name}"
               ToolTip="{Binding Path=Path}" />
</DataTemplate>

特别是我将 setter 属性设置为 IsExpanded 的部分。

如下图所示,这段代码可以正常工作。如果我展开根节点,那么默认情况下所有内容都会展开。

但是为什么根节点默认不展开呢?我不知道它为什么这样做。

【问题讨论】:

    标签: .net wpf xaml treeview expand


    【解决方案1】:

    它们没有被扩展可能是因为您将样式添加到分层数据模板中,并且仅适用于子级(但仅适用于理论)。

    在 DataTemplate 中使用样式是一种代码味道——它是数据的模板,而不是视觉表示,因此它不应该包含 treeViewItem 的样式(下次可能是别的东西,也是分层的)。

    我想你会这样做:

    <TreeView.ItemContainerStyle>
                <Style TargetType="TreeViewItem">
                    <Setter Property="TreeViewItem.IsExpanded" Value="True"/>
                </Style>
     </TreeView.ItemContainerStyle>
    

    【讨论】:

    • 谢谢,成功了。也谢谢你的解释。我确实有一个后续问题(我对 WPF 很陌生) - 如果我没有将它放在分层数据模板中,那么将来我仍然可以将它绑定到 DirectoryItem 对象中的 IsExpanded 属性吗?谢谢
    • 您可以在当前解决方案中使用 {Binding YourPropertyName} 而不是“True”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    相关资源
    最近更新 更多