TreeView Binding in WPF

.net data-binding entity-framework linq wpf


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

ADO.NET Entity Framework Hierarchical Page Class

I want to display this hierarchy in a WPF treeview.

Here's my XAML...

<TreeView Margin="12" Name="TreeViewPages" ItemsSource="{Binding}">
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <TextBlock Text="{Binding Path=ShortTitle}" />

And my VB code...

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?

11/7/2008 5:28:23 PM

Accepted Answer

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.

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.

In your container's declaration (most likely window), you need to define a mapping to the namespace where page is defined.


<Window ...

<TreeView Margin="12" Name="TreeViewPages" ItemsSource="{Binding}" />
        <HierarchicalDataTemplate DataType=”{x:Type local:Page}” ItemsSource="{Binding Children}">
            <TextBlock Text="{Binding Path=ShortTitle}" />
11/7/2008 7:17:15 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow