Thursday, June 24, 2010

Code: WPF Binding a TreeView to an Array of Complex Objects

I’m taking my first stab at WPF as a learning exercise and figured out how to bind an array of objects (with sub-objects) to a TreeView control. 

First, here is the resulting output:

image

 

This TreeView binds to an Array of type ClientWithAssets, which contains an array of Asset and a Client as properties. 

image

Step 1: make sure your sub-objects are public properties and not members! (I was stuck for an hour because of this).

Step 2: Drop a TreeView control on your window and define the hierarchy:

        <TreeView HorizontalAlignment="Stretch" Margin="12,41,12,12" Name="treeView1" VerticalAlignment="Stretch" ItemsSource="{Binding}" >
<
TreeView.ItemTemplate>
<
HierarchicalDataTemplate ItemsSource="{Binding Assets}">
<
TextBlock Text="{Binding ClientItem.ClientName}"/>
<
HierarchicalDataTemplate.ItemTemplate>
<
DataTemplate>
<
TextBlock Text="{Binding Name}"/>
</
DataTemplate>
</
HierarchicalDataTemplate.ItemTemplate>
</
HierarchicalDataTemplate>
</
TreeView.ItemTemplate>
</
TreeView>


Step 3: Bind on window load:



private void Window_Loaded(object sender, RoutedEventArgs e)
{
treeView1.ItemsSource = ClientWithAssets.FindAll();
}

There are many, many ways to perform this same functionality, but this is what made most sense to me.