【问题标题】:Treeview not showing my childrenTreeview 没有显示我的孩子
【发布时间】:2013-11-24 14:38:26
【问题描述】:

我之前没有使用过 TreeView,只是在一些教程中掌握了它们的窍门。我以为我有,结果我没有。

我正在尝试将我的 TreeView 绑定到一个对象。

对象是

public List<MyGrandparents> MyGrandParents {get;set;}

在 MyGrandParent 类中,有一个属性

public List<MyParents> MyParents{get;set;}

最后,在 MyParent 类中有一个属性

public List<MyChildren> MyChildren {get;set;}

在每个类中,还有其他属性,例如名称(虽然没有基类,所以在这个阶段没有共享代码)

我想将地段绑定到树视图,所以在“根”级别我只能看到祖父母。我可以将祖父母扩展到只能看到父母,我也可以将其扩展到看到孩子。

我遇到的问题只是最高级别是绑定(祖父母级别)。我的 XAML 是

<TreeView ItemsSource="{Binding MyGrandParents}">
        <TreeView.Resources>
            <DataTemplate DataType="{x:Type local:MyGrandParent}">
                    <TextBlock Text="{Binding Name}" Margin="0,0,10,0" />
            </DataTemplate>
            <HierarchicalDataTemplate DataType="{x:Type local:MyParent}" ItemsSource="{Binding MyGrandParents}">
                    <TextBlock Text="Don't bind to test"></TextBlock>
            </HierarchicalDataTemplate>
        </TreeView.Resources>            
    </TreeView>

我不明白为什么这不能给我一棵漂亮的树。

【问题讨论】:

    标签: c# wpf xaml treeview


    【解决方案1】:

    您没有遵循正确的模式来使用HierarchicalDataTemplate

    可能contain children 的项目应声明为HierarchicalDataTemplate,并将ItemsSource 设置为child collection,您希望在其下方显示。

    item not containing any child 应该声明为DataTemplate

    应该是这样的-

    <TreeView.Resources>
       <HierarchicalDataTemplate DataType="{x:Type local:MyGrandParent}"
                                 ItemsSource="{Binding MyParents}">
            <TextBlock Text="{Binding Name}" Margin="0,0,10,0" />
       </HierarchicalDataTemplate>
       <HierarchicalDataTemplate DataType="{x:Type local:MyParent}"
                                 ItemsSource="{Binding MyChildren}">
            <TextBlock Text="Don't bind to test"></TextBlock>
       </HierarchicalDataTemplate>
       <DataTemplate DataType="{x:Type local:MyChildren}">
            <TextBlock Text="Don't bind to test"></TextBlock>
       </DataTemplate>
    </TreeView.Resources>
    

    【讨论】:

    • 我是不是在向后尝试?儿童是最低级别,但在您的示例中,它似乎是最高级别? DataTemplate 是“根”而所有 HierarchicalDataTemplates 是孩子吗?
    • 更新了答案和解释。看看吧。
    • 谢谢!过去一个小时我一直在阅读教程,但没有一个教程清楚地解释了TreeView 的使用。
    猜你喜欢
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多