Linq查询到树视图HierarchicalDataTemplate [英] Linq query to treeview HierarchicalDataTemplate

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

问题描述

首先,对不起我的英语不好. 我有一个EF实体,如下所示:

First, sorry for my bad english. I have an EF entity that looks like:

class Item
{    
    public Guid Id { get; set; }
    public string Title{ get; set; }
    public Guid? ParentId { get; set; }
    public ICollection<Item> Items { get; set; }    
}

现在,我想从该实体上的树视图中加载数据...我能得到的最好的是以下xaml:

Now i want to load the data from that entity on a treeview... the best I could get is the follow xaml:

<TreeView Name="treeItems">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate DataType="{x:Type local:Item}" ItemsSource="{Binding Items}">
            <TextBlock  Text="{Binding Path=Title}" />
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

并使用

var itens = from it in ctx.Item select it;
treeItems.ItemsSource = itens;

这显然会在树状视图上显示数据,如下所示:

This obviously displays the data on the treeview like this:


ItemA
  ItemA1
  ItemA2
ItemA1 --repeated node
ItemA2 --repeated node

如何调整(或重写)我的代码,使树状视图以分层方式显示数据,而无需重复节点?

How can i tweak (or rewrite) my code so the treeview displays the data in hierarchical way, without the repeated nodes?

推荐答案

假定树的结构已经构建,则只需要在层次结构的第一级中包括根项即可;因此,例如,您要编写treeItems.ItemsSource = itens.Where(i => i.ParentId == null)(可选地,后跟ToList()).模板很好.

Assuming the structure of the tree is already built, you only need to include the root items in the first level of the hierarchy; so, for example, you'd write treeItems.ItemsSource = itens.Where(i => i.ParentId == null) (optionally followed by ToList()). The template is fine.

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

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