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:

xmlns:System="clr-namespace:System;assembly=mscorlib"
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"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation%22
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml%22
xmlns:System="clr-namespace:System;assembly=mscorlib"
Title="TreeViewTest" Height="300" Width="300">

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


And the Code behind:


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

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