为什么我的TreeView看起来像这样?

时间:2017-01-23 10:16:32

标签: wpf xaml treeview

    <TreeView SelectedValuePath="{Binding Id}" ItemsSource="{Binding MySourceHere}">
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type LocalCategories:BaseCategory}" ItemsSource="{Binding Subcategories}">
                <TreeViewItem IsExpanded="True">
                    <TreeViewItem Header="{Binding DisplayName}" />
                </TreeViewItem>
            </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>

enter image description here

标记TreeViewItem的正确方法是什么,如果不是<TreeViewItem Header="text" />

如果我删除了HierarchicalDataTemplate它渲染得很好,但当然我失去了层次结构。

enter image description here

修改

应该是

<TreeViewItem IsExpanded="True" Header="{Binding DisplayName}" />

然而,它仍然看起来很奇怪,为什么我的项目中有一个盒子?

enter image description here

1 个答案:

答案 0 :(得分:1)

HierarchicalDataTemplate不应包含TreeViewItem。试试这个:

<TreeView SelectedValuePath="{Binding Id}" ItemsSource="{Binding MySourceHere}">
    <TreeView.ItemContainerStyle>
        <Style TargetType="TreeViewItem">
            <Setter Property="IsExpanded" Value="True"/>
        </Style>
    </TreeView.ItemContainerStyle>
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type LocalCategories:BaseCategory}" ItemsSource="{Binding Subcategories}">
            <TextBlock Text="{Binding DisplayName}" />
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>