Friday, 7 August 2009

WPF TreeView – Different DataTemplate for Different Data Types

Have you wondered how you can show or edit different types of data using different DataTemplates in a TreeView? It is actually pretty easy – here is a way to do it:

The key is simple DataType="{x:Type System:String}" attribute for the DataTemplate which identifies for which Type will the DataTemplate be used. Here the System: is just a namespace import and String is the type:

Here is the complete Example that shows data of types String, Int32 and Double in different colors and a note of the type before the value:

<Window x:Class="Blog.TreeViewExample"
Title="TreeViewTest" Height="300" Width="300">

<TreeView x:Name="TreeView" ItemsSource="{Binding}">
<DataTemplate DataType="{x:Type System:String}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="(System.String): "></TextBlock>
<TextBlock Foreground="Blue" FontWeight="Bold" Text="{Binding}" />
<DataTemplate DataType="{x:Type System:Double}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="(System.Double): "></TextBlock>
<TextBlock Foreground="Green" FontWeight="Bold" Text="{Binding}" />
<DataTemplate DataType="{x:Type System:Int32}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="(System.Int32): "></TextBlock>
<TextBlock Foreground="Red" FontWeight="Bold" Text="{Binding}" />

And the Code behind:

namespace Blog
/// <summary>
Interaction logic for TreeViewTest.xaml
/// </summary>
public partial class TreeViewExample : Window
public TreeViewExample()

// Some sample data with different Types
TreeView.DataContext = new List<System.Object> {
(System.String) "Item1",
(System.Int32) 1,
(System.Double) 2.0 };
Enjoy ! Tzanimir

1 comment: