WPF TreeView绑定 [英] WPF TreeView Binding

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

问题描述

我有一个班级与父母和儿童的属性。

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

ADO.NET实体框架分层页面类http://img148.imageshack.us/img148/6802/edmxxe8.gif

我想在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代码...


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?

推荐答案

为什么这不工作的原因是你只是指定TreeView的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放在TreeView(或其任何父视觉效果)的资源中,并设置DataType 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 TreeView绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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