Linq query to treeview HierarchicalDataTemplate

偶尔善良 提交于 2019-12-24 21:17:15

问题


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

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>

and load the data with

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?


回答1:


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.



来源:https://stackoverflow.com/questions/3597099/linq-query-to-treeview-hierarchicaldatatemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!