.net WPF 树视图绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/272854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 10:32:23  来源:igfitidea点击:

WPF TreeView Binding

.netwpflinqentity-frameworkdata-binding

提问by Zack Peterson

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

我有一个带有 Parent 和 Children 属性的类。

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

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

I want to display this hierarchy in a WPF treeview.

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

Here's my XAML...

这是我的 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...

还有我的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?

但后来我只得到一棵树两层深。我需要做什么才能让它发挥作用?

回答by Abe Heidebrecht

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.

这不起作用的原因是您只为 TreeView 指定了 DataTemplate。由于它生成的 TreeViewItems 也是 ItemsControls,它们也需要设置 ItemTemplate。

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.

实现您所希望的最简单方法是将 HierarchicalDataTemplate 放在 TreeView(或其任何父视觉对象)的资源中,并设置 HierarchicalDataTemplate 的 DataType,以便将其应用于您的所有项目。

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>