Geeks With Blogs


Timmy Kokke's Blog

↑ Grab this Headline Animator

Timmy Kokke at Blogged
Timmy Kokke …just sorting my bubbles…


Today I would like to show you how to style a TreeView control in Silverlight 3 using Expression Blend 3. The TreeView is a control to visualize hierarchical data structures. If you haven’t got Silverlight 3 and Blend 3, you can find all downloads for Silverlight 3 and Blend 3 here. The TreeView control is available in WPF natively and styling is only a small bit different than in Silverlight. I try to explain one way of doing this and there are others. If you have any questions what so ever or suggestions for other tutorials, please let me know.


Initial Startup

We’ll start by creating a new Silverlight 3 Application project.


Go to the new Assets panel and find select the TreeView control from the controls section.


Add the TreeView to the RootLayout Grid by dragging it from the Asset panel to the edit area. Make it span the entire area by setting the margins to 0, the horizontal and vertical alignment to stretch and the width and height to Auto. At this point nothing is visible, because there’s no data yet.

Sample Data

One of the features I really like in Expression Blend 3 is the generation of sample data. By using sample data you don’t have to wire your application up to a real data source and making it available when designing an application. Often I create sample data in Blend 3 to add it to parts of my production work in Blend 2.

A TreeView uses hierarchical data, which often are collections in collections in collections etc. I would like to have three different types of data all in collections. Create the first collection of data by going to the Data panel, click the Add sample data source icon and select Define New Sample Data…


Make sure the Enabled sample data when application is running checkbox is checked, so that you can see the result of the styled checkbox when running the application. Accept all other settings and hit the Ok button.


Rename the default collection to RootLevelCollection.


To quickly test you TreeView you can convert the RootLevelCollection to a Hierarchical Collection, which basically means that the collection is referencing itself. To do this, click on the little dropdown list at the end of the RootLevelCollection line and click Convert To Hierarchical Collection.


Immediately a collection is added to the RootLevelCollection. If you open this, you’ll find the same properties as the first level, including the collections. You can open these collections as long as you want.

In this tutorial I would like to show you how to use different templates on different types of levels in you collection. The recursive collection can be removed again by right clicking on the “child” RootLevelCollection and hit Remove.


Change the type of Property1 to number by clicking on the little abc icon at the end of the line and select number from the dropdown list. Rename the property to NumberProperty.


Add a simple property and by clicking on the plus icon and rename it to NameProperty.


Change the string format by clicking on the abc icon and select Name from the Format dropdown list.


Add a new collection to the RootLevelCollection by clicking on the little down arrow on the same line and select Add Collection Property. Rename this to FirstLevelCollection.AddSampleCollection

Repeat the steps above to end up with the following properties:



  • NameProperty – Simple Property of String (Format: Name)
  • NumberProperty – Simple Property of Number
  • FirstLevelCollection – Collection Property


  • CompanyProperty – Simple Property of String(Format: Company Name)
  • NumberProperty – Simple Property of Number
  • UrlProperty – Simple Property of String(Format: Website Url)
  • SecondLevelCollection – Collection Property


  • ImageProperty – Simple Property of Image
  • NameProperty – Simple Property of String(Format: Name)
  • PhoneProperty –Simple Property of String(Format: Phone number)

The sample data tree should look something like this. I added a few red lines to make the structure of the tree a bit  more clear.


To bind the sample data to the TreeView, drag the RootLevelCollection to the TreeView element in the Objects and Timeline Panel. You should see some of the data appear in the tree immediately. although it doesn’t look very much like a tree yet.

Creating Hierarchical Data Templates

To show the data in the best way possible, every type of data needs it’s own Data Template. The HierarchicalDataTemplate, that you might know from WPF. The Silverlight version doesn’t include all methods and properties the WPF version does, but provides an easy way to style hierarchical data.

Due to a bug in Silverlight, Expression Blend will show an error when using nested Hierarchical Data Templates. There seems to be a problem in the xaml parser, which says the xaml is invalid. But it isn’t and the application will run anyway. I’ll show you how to work around this error. Let’s hope this gets fixed in the final release.

This annoying bug has been fixed in the release version! The templates work like they should now. Microsoft has made some big improvements in this area. Everything can be done in Expression Blend 3 now and it can be done without having to write anything in xaml. But, I think I might be useful to learn how the Data Templates are build in xaml and because this was the way it was written in the betas, I’ll stick with that. More tutorials will follow and the creation of templates by right clicking your mouse will be covered without a doubt.

Because the sample data created earlier contains three levels, three collections of a different class, three different data templates are needed to show the data properly. To keep these templates separated and enable the possibility to share the templates between different pages and UserControls very easy, I prefer to put data templates in there own Resource Dictionary. A resource dictionary is a xaml file that contains only resources. To add a new dictionary to your project click File –> New Item… and select Resource Dictionary from the list. If you want you can give it a useful name, for now, just accept the default by clicking Ok.


Now you need to link the new resource dictionary to the TreeView so it can access the templates. Go to the Resource panel and right-click [TreeView]  control, select Link to Resource Dictionary and click ResourceDictionary1.xaml.

LinkToResourceDictionary Right-click ResourceDictionary1.xaml in the resource panel and hit View XAML to open the resource dictionary.

ViewXaml To make use of a HierarchicalDataTemplate xaml, you first need to reference it’s namespace. Do this by adding the following line to the opening ResourceDictionary tag at the beginning of the file:


The hierarchical data template has three dependency properties. For now, use only the ItemSource property. The ItemSource property can be bound to the collection used for the next level in the hierarchical tree. In this example this would be the FirstLevelCollection. The contents of the data template are not very special. Just an horizontal oriented StackPanel with two TextBlocks. The first one is bound to the NumberProperty and is slightly bigger than the other. That one is bound to the NameProperty of the root sample data class. Add a small margin to give the TextBlocks a little more space.

<common:HierarchicalDataTemplate x:Key="RootLevel"
         ItemsSource="{Binding Path=FirstLevelCollection}">
    <StackPanel Orientation="Horizontal">
        <TextBlock Margin="5,0,3,0"
                   Text="{Binding Path=NumberProperty}" 
                   FontWeight="Bold" FontSize="12" />
        <TextBlock Margin="3,0,5,0"
                   Text="{Binding Path=NameProperty}" />

This data template needs to be known by the TreeView. Right-click on the TreeView control in the Objects and Timeline Panel and go to Edit Other Templates –> Edit Generated Items(ItemTemplate) –> Apply Resource and select RootLevel from the list.

SetItemTemplate You should see some changes to the tree now. It doesn’t look a lot like a tree yet. To style the second level of the tree, add another HierarchicalDataTemplate to the ResourceDictionary. This template has to be defined before it’s used, which will be by the root template. It looks similar to the template above, only the key and the bindings are different. This template has it’s ItemSource bound to the collection for the second level, SecondLevelCollection.

<common:HierarchicalDataTemplate x:Key="Level1"                 
        ItemsSource="{Binding Path=SecondLevelCollection}">
    <StackPanel Orientation="Horizontal">
        <TextBlock Margin="5,0,3,0" 
                   Text="{Binding Path=NumberProperty}" />
        <TextBlock Margin="3,0,3,0" 
                   Text="{Binding Path=CompanyProperty}" />
        <TextBlock Margin="3,0,5,0" 
                   Text="{Binding Path=UrlProperty}" />

At this point nothing will happen, because the two templates need to be connected. The HierarchicalDataTemplate uses a dependency property, similar to the one on the TreeView, to do this: ItemTemplate. To use the Level1 data template as an item template add the following line to the start tag of the RootLevel template:

            ItemsSource ="{Binding Path=FirstLevelCollection}"
            ItemTemplate="{StaticResource Level1}">

There's only the second level of the template left to style. It’s similar to the other two. Bind the source of the image to the ImageProperty and set it’s width and height to 25.

<common:HierarchicalDataTemplate x:Key="Level2">
    <StackPanel Orientation="Horizontal">
        <TextBlock Margin="5,0,3,0" 
                   Text="{Binding Path=NameProperty}" />                    
        <TextBlock Margin="3,0,3,0" 
                   Text="{Binding Path=PhoneProperty}" />
        <Image Margin="3,0,5,0" 
               Height="25" Width="25" 
               Source="{Binding Path=ImageProperty}"/>                                        

Don’t forget to set the ItemSource property on the Level1 template to Level2 when running the application.

To quickly access the templates for editing. Select the MainControl.Xaml file for editing and go to the Resource panel. When you expand the ResourceDictionary1.xaml dictionary file, you can open the templates for editing by clicking on the button next to the template names:


When running the application should look something like:

RunningApp1 It looks like a tree now, but not a very awesome one. Let’s style it a little further.

Creating Control Templates

To make the tree look a little better, you need to change its ItemContainerStyle.


Give it a fancy name. To add it to the ResourceDictionary select the Resource dictionary radio button in the define in section. Hit OK to confirm and close the window.


To get to the template, right-click the Style element and select Edit Control Parts –> Edit Template.EditContainerStyleTemplateThe TreeViewItemTemplate consists of 3 important parts: the Header, which represents one item; ItemsHost, which represents the child items of the header (these items can be headers with children too); and the ExpanderButton, which is the indicator if a header is expander or not. First, lets change the look and feel of the ExpanderButton.

Right-Click the ExpanderButton element and select Edit Control Parts(Template) –> Edit Template.

editExpanderButtonTemplate The default template contains a couple of grids and two paths. These are unnecessary, so delete the [Grid] element including the two paths. The paths were animated, so ignore the message about this.

Add a Border to the Root grid element. Start by giving it a fixed width and height of 24. Change its Corner Radii to 8,3,3,8 and its Border Thickness to 1,2,1,1 to give it a little flow to the right. Change the Border Color to a gradient, starting and ending on a darkish blue color like #FF0D0A45. Add a Gradient Stop at about 20% and make this a little whiter than the start and end. Set the Background Color to a SolidBrush and change its color to a lighter version of the gradient, like #FF5C5A88.

Next, add a Grid to the border and make sure all properties are set to their defaults. Add two TextBlocks to he grid and name them PlusSign and MinusSign. Type in the PlusSign textblock a “ + “ and in the MinusSign textblock a “ – “. Set the Horizontal- and the Vertical Alignment on both textblocks to Center. Change their fonts to Verdana, make them Bold and increase their sizes to 18. Set the Foreground Color to full white on both. Hide the MinusSign by default by setting its opacity to 0. This only has to become visible when the tree is expanded.


The Xaml should look something like:

<Border x:Name="border" 
        Width="24" Height="24" 
        <LinearGradientBrush EndPoint="0.5,1" 
            <GradientStop Color="#FF0D0A45" Offset="0"/>
            <GradientStop Color="#FF0D0A45" Offset="1"/>
            <GradientStop Color="#FF3A385B" Offset="0.2"/>
        <TextBlock x:Name="PlusSign" 
                   Text="+" TextWrapping="Wrap" 
                   FontFamily="Verdana" FontWeight="Bold" 
                   Foreground="#FFFFFFFF" FontSize="18"/>
        <TextBlock x:Name="MinusSign" 
                   Text="-" TextWrapping="Wrap"
                   FontFamily="Verdana" FontWeight="Bold" 
                   FontSize="18" Opacity="0" 

The change to looks of ExpanderButton when it is checked, you can use the Visual State Manager. Go to the States panel and select Checked under the CheckStates Visual State Group. Notice the red border around the drawing area, this indicates that every change you make is recorded and stored in this particular Visual State.



With the Checked State selected, change the Opacity of the MinusSign element to 100 and of the PlusSign to 0. At this point the MinusSign is visible when the TreeView is expanded.  Change the Corner Radii of the Border to 8,8,3,3 and the Thickness to 1,1,1,2. minusSign

The Xaml for the Checked State is placed inside the code for the Visual State Manager. It should look something like:

<vsm:VisualState x:Name="Checked">
        <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" 
            <EasingDoubleKeyFrame KeyTime="00:00:00" Value="1"/>
        <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" 
            <EasingDoubleKeyFrame KeyTime="00:00:00" Value="0"/>
        <ObjectAnimationUsingKeyFrames BeginTime="00:00:00" 
            <DiscreteObjectKeyFrame KeyTime="00:00:00">
        <ObjectAnimationUsingKeyFrames BeginTime="00:00:00" 
            <DiscreteObjectKeyFrame KeyTime="00:00:00">

To make the tree a bit more user friendly, you want to highlight the ExpanderButton when the mouse cursor is hovering. Got to the States panel and select MouseOver this time. It’s in the  Common States Visual State Group. To keep the same gradient it would be nice if you could only shift the colorization. You can do this by changing the color mode setting. If you look at a color editor, notice that there the R, G and B are underlined. When you click on one a small listbox pops up and you can change the color mode. If you change it to HSL, Hue – Saturation – Lightness, you have the possibility to shift the Hue, which happens to be the colorization.


Change the Hues for the the Border gradient  and for the Background color to 48.

To position the ToggleButton properly, remove the second column of the root Grid of the template and set the width of the first column to 32 and the with of the now second column to 1 star. The same goes for the two rows, the first to 32 pixels and the second to 1 star. Making this piece of xaml look something like:

<Grid Background="{x:Null}">
        <ColumnDefinition Width="32"/>
        <ColumnDefinition Width="*"/>
        <RowDefinition Height="32"/>
        <RowDefinition Height="*"/>

Click the button with the arrow next to ToggelButton Template in the Objects and Timeline panel to leave the template.


To place the child items in a container, right click the ItemsHost element in the Objects and Timeline panel and select Group into… and select Grid, or press Ctrl+G on the keyboard. Make sure all properties are set to their defaults, the Grid tag in xaml should be empty. Next, right click the Grid you’ve just added and go to Group into… again, but this time select Border. Give this border a gradient for its Background brush and make it go from an almost white purple to just a little darker than that, like from #FFD4D2F9 to #FF908BEE. The BorderBrush for this border will be the same as the border used for the ToggleButton explained earlier. Set the border Thickness to 1 on all four to make the border visible. Change the border’s CornerRadius to 1,4,8,4 to give a modern look.

Change the location of the border to row 1, column 1, rowspan 1 and gridspan 1. To make the border indent less that 32 pixels, but keeping it bound to the second column, change the Left Margin to –27. This will make it look like its indentation is only 5 pixels, but, to keep the TreeView work correctly, resize it only to the second column. Set the Left Padding to 5 to let the contents of the border indent even a little more.

When you run the application at this point, a small line will be shown for every item of the TreeView. This is cause by the Visual State Manager only hiding and showing the ItemsHost at this time. To make the entire border disappear, copy the following two properties from the ItemsHost to the Border in the xaml editor.


The border will be named ItemsHost now. And when you run the application, the border should become visible when TreeView Items are expanded. It is possible you’ll see an error when the properties are removed from the ItemsHost. I assume this is cause by the same bug as with the Hierarchical templates. If you want to make the border visible again, move these properties back to the ItemsHost, which is now called ItemsPresenter,  its default name. If you want to see the Border with its contents again, select the Expanded state in the Visual State Manager.


I personally like a shiny edge on borders. It’s very easy add that little spark. Start by adding a rectangle to the grid and place this above the ItemsPresenter(this used to be ItemsHost) element in the same grid. Keep the width and height of 100. Set the Fill to No Brush to make its background transparent. The Stroke brush has to be set to a gradient, going from fully transparent white to 50% transparent white. Set its radii to 8 and its StrokeThickness to 1.  Make it Horizontally align to the Right  and the Vertical alignment to the Bottom. Set the right and bottom margins to 3, keeping the left and top margins 0. The last part is best done in xaml and has to do with the start and end positions of the gradient. The gradient needs a StartPoint of 0.7, 0.7 and an EndPoint of 1.0,1.0. The xaml for the rectangle:

<Rectangle Fill="{x:Null}" 
           RadiusX="8" RadiusY="8" 
           Width="100" Height="100" 
            <GradientStop Color="#00FFFFFF" Offset="0"/>
            <GradientStop Color="#7FFFFFFF" Offset="1"/>

Before running the application, make sure you’ve cut-pasted the ItemTemplates to the right places in the Hierarchical data templates and set the Visibility and Name properties correctly on the Border in the TreeViewContainerStyle. You can just hit F5 in the new release and your application will run line a charm.

Where to go from here

This tutorial only showed what can be done styling the TreeView, which templates are available, and where can they be found. Imagine what you can do with real data, creating a style that looks and feels one with the data. You can even go beyond the basic TreeView and create multiple columns or a Tab-like style.

One place I want to mention is the blog of Bea Stollnitz. On her blog she give a lot of information and explanation about TreeViews and ListViews, for WPF and Silverlight.

The code for the tutorial can be downloaded here.

Shout it dotNed blogger
kick it on
Posted on Monday, June 29, 2009 8:33 AM Silverlight , Blend | Back to top

Comments on this post: Styling a TreeView in Silverlight 3 and Blend 3

# re: Styling a TreeView in Silverlight and Blend 3
Requesting Gravatar...
This is a great article, thanks! Just wanted to let you know that for Blend 3 RTM, we have fixed a number of the limitations you listed above and also now support automatic generation of HDT when you drag and drop a recursive collection onto the TreeView control! So hopefully the TreeView would be even easier to use.
Left by Unni Ravindranathan - MSFT on Jun 29, 2009 10:51 AM

# re: Styling a TreeView in Silverlight 3 and Blend 3
Requesting Gravatar...
Yep, Excellent article once again Timmy.

I really loved the style of the article. Going between Code, Images and visuals aids. It makes the article uber-easy to read IMO.

And I also loved how you created an end-to-end solution here on getting Styled DataBound TreeView to work.

I'll expand a bit on what Unni was saying. There's really amazing tooling for Hierarchical Data Sources in Blend 3 RTM going online that'll make the TreeView Sample Data story much simpler. Make sure to update this post when it goes live :)

Excellent blog post,
-- Justin Angel
Microsoft Silverlight Program Manager
Left by Justin Angel on Jul 03, 2009 3:21 PM

# re: Styling a TreeView in Silverlight 3 and Blend 3
Requesting Gravatar...
You are voted!
Track back from
Left by on Jul 04, 2009 3:05 AM

# Sample Data
Requesting Gravatar...
The sample data isn't working for me. It seems converting the collection to a hierarchical structure creates multiple instances of that same structure as children. Your instructions don't address this at all. Then, with just a collection data type, it seems I get an error when I attempt to apply the [<common:HierarchicalDataTemplate x:Key="Level1"] code. Anyone else have this problem?
Left by Joel on Sep 16, 2009 1:19 AM

# re: Styling a TreeView in Silverlight 3 and Blend 3
Requesting Gravatar...
The "convert to hierarchical collection" creates an infinite loop to itself. This way you can view and style a TreeView without having to think about the different depths of the data. In the case of this example I did not use this functionality and create a 3 level datastructure by hand to show how to give each level its own style. You have to remove the recursion to get the sample to work.
Left by Timmy Kokke on Sep 16, 2009 9:43 AM

# re: Styling a TreeView in Silverlight 3 and Blend 3
Requesting Gravatar...

Nice article, but one thing I noticed if that if you click on a leaf node then it gets a empty box expanded beneath. Any way to turn this off?
Left by Colin on Nov 05, 2009 3:59 PM

# re: Styling a TreeView in Silverlight 3 and Blend 3
Requesting Gravatar...
Hi, Good Stuff:
Few things, and I am a Silverlight Noob so maybe I am missing something BUT:
1) The order in which the HierarchicalDataTemplate is defined in the dictionary seems to matter. If I put Root 1st, then Level 1 then Level 2...the compiler (in VS, not Expression) would complain that no item named Level 1 exists. Once I put it L2/L1/root, no problems.

2) In your sample code, you have:
ItemsSource="{Binding Path=SecondLevelCollection}"
but here you have
ItemsSource="{Binding SecondLevelCollection}"

both ways work, but is one way better than the other.

Left by melegant on Dec 16, 2009 11:19 PM

# re: Styling a TreeView in Silverlight 3 and Blend 3
Requesting Gravatar...
Great Article. it solved my many issues.
Left by Asad on Apr 16, 2010 1:54 PM

# re: Styling a TreeView in Silverlight 3 and Blend 3
Requesting Gravatar...
Was very helpful and well presented. Thanks
Left by GiriMud on Jun 17, 2010 3:18 PM

# re: Styling a TreeView in Silverlight 3 and Blend 3
Requesting Gravatar...
Hey, loved your tutorial, but I'm having trouble using it for my application. Would you mind taking a look at this thread?

Left by JGord on Jun 30, 2010 4:38 PM

# now how to add drag and drop? (Blend 4)
Requesting Gravatar...
This is a very informative article! Thanks for clearing up a lot of questions.

How do you suppose you could add drag and drop to this? For instance, in your top illustration, how could you click on "55. A Datum Corporation" and drag it to say, "79. Barber, David" so all the entries would drop under David's name and do a two-way update to the associated database?

Thanks! Any help would be moooost appreciated.
Left by jdavis on Jul 13, 2010 2:58 PM

# re: Styling a TreeView in Silverlight 3 and Blend 3
Requesting Gravatar...
I tried the resource distionary in a sketch flow application and I got an error saying that HierarchicalDataTemplate was not in the namespace.
I changed the assembly to PresentationFramework which seems to be the assembly according to '' and it built. I'm not sure why.
Left by Samuel on Oct 12, 2010 1:58 PM

# re: Styling a TreeView in Silverlight 3 and Blend 3
Requesting Gravatar...
the download code is offline please update

Thanks great post
Left by Jesus Estevez on Feb 14, 2012 11:10 AM

Your comment:
 (will show your gravatar)

Copyright © Timmy Kokke | Powered by: