WPF TreeView Binding [duplicate]

南楼画角 提交于 2020-02-20 07:37:26

问题


I've got a class with Parent and Children properties.

ADO.NET Entity Framework Hierarchical Page Class http://img148.imageshack.us/img148/6802/edmxxe8.gif

I want to display this hierarchy in a WPF treeview.

Here's my XAML...

<TreeView Margin="12" Name="TreeViewPages" ItemsSource="{Binding}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <TextBlock Text="{Binding Path=ShortTitle}" />
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

And my VB code...

Dim db As New PageEntities
Dim t = From p In db.Page.Include("Children") _
        Where p.Parent Is Nothing _
        Select p
TreeViewPages.ItemsSource = t

But then I only get a tree two levels deep. What do I need to do to get this working?


回答1:


The reason why this isn't working is that you are only specifying the DataTemplate for the TreeView. Since the TreeViewItems that it generates are also ItemsControls, they would need to have the ItemTemplate set as well.

The easiest way to achieve what you are hoping for is to put the HierarchicalDataTemplate in the resources of the TreeView (or any of its parent visuals), and set the DataType of the HierarchicalDataTemplate so it is applied to all of your items.

In your container's declaration (most likely window), you need to define a mapping to the namespace where page is defined.

e.g.

<Window ...
    xmlns:local="clr-namespace:NamespaceOfPageClass;assembly=AssemblyWherePageIsDefined">

<TreeView Margin="12" Name="TreeViewPages" ItemsSource="{Binding}" />
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType=”{x:Type local:Page}” ItemsSource="{Binding Children}">
            <TextBlock Text="{Binding Path=ShortTitle}" />
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>


来源:https://stackoverflow.com/questions/272854/wpf-treeview-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!