Stephen on Software aka SOS

July 22, 2009

Binding WPF Treeview and Objects

Filed under: Programming — Tags: — sljm @ 9:49 pm

I have been trying to find some resources for using custom objects as data for WPF TreeView for my own little project.

I most useful/closest to what I wanted to do was by Mike Hillberg but still its a bit complex for my needs. I just needed something simple. What I had was a Dir objects that has a List of Directories inside, which i wanted to display in the TreeView

public class Dir
{
public Dir(){}

public List<Dir> Directories{get;set;}
....
}

The code for the Dir class.

What you need now is a template or more specifically a HierarchicalDataTemplate that tells the TreeView how to read your object.

<Window x:Class="TaggerGui.Window1"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:local="clr-namespace:TaggerGui"
 Title="Window1" Height="600" Width="600">

.......

<TreeView Grid.Column="0" Name="FileTree" ItemsSource="{x:Static local:Window1.dirs}">
 <TreeView.ItemTemplate>
 <HierarchicalDataTemplate ItemsSource="{Binding Path=Directories}">
 <StackPanel Orientation="Horizontal">
 <TextBlock Text="{Binding Path=Name}"/>
 </StackPanel>
 </HierarchicalDataTemplate>
 </TreeView.ItemTemplate>
 </TreeView>

.....
</Window>

In this case I declare a static public ObservableCollection<File> dirs=new ObservableCollection<File>(); in the cs file and bind that using the x:static binding. Remember that you have to add the reference to the namespace that you are using at the top of the xaml file, (theĀ  xmlns:local=”clr-namespace:TaggerGui”) part

Okies now for the next problem, let say i want to display different colors in the tree depending on how the presence of a certain file in the directory. How would you do that ? Well I am looking at the MVVM or the Model View View Model Pattern, that would be another blog post.

Links:

An Example of using Objects with Observable Collection in TreeView – Mike Hillberg

Gird Splitter

Hierarchical Databinding in WPF

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.