views:

22

answers:

1

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  A: 

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.

Alex Paven
wow... this is so obvious :/ ... at first i thinked that the where clause would not load the non null itens... thinking too much in SQL/Winform and little in EF/WPF I guess... thank you for your help :)
Leo