WPF树视图绑定视图、绑定、WPF

2023-09-04 01:12:04 作者:①直赖着沵

我有一类家长和儿童的属性。

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

我想在WPF树视图中显示此层次结构。

I want to display this hierarchy in a WPF treeview.

下面是我的XAML ...

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>

和我的VB code ...

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?

推荐答案

这是为什么不工作的原因是,你只指定了DataTemplate中的树视图。因为它生成的TreeViewItems也ItemsControls,他们将需要具有的ItemTemplate设置为好。

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.

要达到你希望什么,最简单的方法就是把HierarchicalDataTemplate在树视图(或任何其父视觉效果)的资源,并设置HierarchicalDataTemplate的数据类型,因此适用于所有的项目。

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.

例如。

<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>