WPF树视图绑定 [英] WPF TreeView Binding

查看:93
本文介绍了WPF树视图绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

这篇关于WPF树视图绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆