开发者

Linq query to treeview HierarchicalDataTemplate

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;开发者_JAVA百科 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜