Click here to Skip to main content
Click here to Skip to main content

Custom TreeView Layout in WPF

By , 24 Jan 2007
 

Introduction

This article discusses how to customize the item layout in a WPF TreeView. The layout we will examine is quite similar to an "org chart", where each level of items is displayed in a horizontal row directly beneath their respective parent. Along the way we will see how the power of templates and styles in WPF can provide incredible flexibility for customizing an application's user interface.

This article is not for WPF beginners. It assumes that you already have knowledge of XAML, control templates, styles, triggers, hierarchical data templates, data binding, and other fundamentals of WPF.

I also posted another article regarding layout customization for the TreeView control. If you are interested in seeing another way that the TreeView can be customized, you might want to read Advanced Custom TreeView Layout in WPF.

Graphical overview

Before diving into the XAML which makes the magic happen, let's first take a look at what we are aiming to achieve. If I populate a TreeView with some simple data and view it, by default it looks pretty plain. Here is the "before" picture:

Before

What you see above is certainly not a breathtaking representation of the data. However, after we customize the way that TreeViewItems are rendered and how the TreeView positions its items, the same TreeView control can look like this:

After

How it works

The first step is to create a custom ControlTemplate for the TreeViewItem class. If you wrap that template in a typed Style (i.e. a Style with no Key) then it will automatically be applied to every TreeViewItem instance by default. The TreeViewItem control template should have two things: a ContentPresenter whose Name is 'PART_Header' and an ItemsPresenter. The ContentPresenter is used to display the content of the item. The ItemsPresenter is used to display it's child items.

In addition to customizing the TreeViewItem control template, you also must modify the ItemsPanel of TreeViewItem. In order for the child items to be displayed in a horizontal row, I set the TreeViewItem.ItemsPanel property to a StackPanel with a horizontal orientation. That setting was also applied in the typed Style mentioned previously.

Let's take a look at an abridged version of the typed Style:

<Style TargetType="TreeViewItem">
  <Style.Resources>
    <!-- Resources omitted for clarity… -->
  </Style.Resources>
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="TreeViewItem">
        <Grid Margin="2">
          <Grid.RowDefinitions>
            <!--The top row contains the item's content.-->
            <RowDefinition Height="Auto" />
            <!--The bottom row contains the item's children.-->
            <RowDefinition Height="*" />
          </Grid.RowDefinitions>

          <!-- This Border and ContentPresenter displays the
               content of the TreeViewItem. -->
          <Border Name="Bd"
            Background="{StaticResource ItemAreaBrush}"
            BorderBrush="{StaticResource ItemBorderBrush}"
            BorderThickness="0.6"
            CornerRadius="8"
            Padding="6"
            >
            <ContentPresenter Name="PART_Header"                 
              ContentSource="Header"
              HorizontalAlignment="Center"
              VerticalAlignment="Center" />
          </Border>

          <!-- The ItemsPresenter displays the item's children. -->
          <ItemsPresenter Grid.Row="1"/>
        </Grid>

        <ControlTemplate.Triggers>
          <!--When the item is selected in the TreeView, use the
              "selected" colors and give it a drop shadow. -->
          <Trigger Property="IsSelected" Value="True">
            <Setter
              TargetName="Bd"
              Property="Panel.Background"                    
              Value="{StaticResource SelectedItemAreaBrush}" />
            <Setter
              TargetName="Bd"
              Property="Border.BorderBrush"                    
              Value="{StaticResource SelectedItemBorderBrush}" />
            <Setter
              TargetName="Bd"
              Property="TextElement.Foreground"                  
              Value="{DynamicResource
                {x:Static SystemColors.HighlightTextBrushKey}}" />
            <Setter
              TargetName="Bd"
              Property="Border.BitmapEffect"                 
              Value="{StaticResource DropShadowEffect}" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>

  <!-- Make each TreeViewItem show it's children
       in a horizontal StackPanel. -->
  <Setter Property="ItemsPanel">
    <Setter.Value>
      <ItemsPanelTemplate>
        <StackPanel
          HorizontalAlignment="Center"
          IsItemsHost="True"
          Margin="4,6"
          Orientation="Horizontal"  />
      </ItemsPanelTemplate>
    </Setter.Value>
  </Setter>
</Style>

The final step is to make the TreeView center the root item(s) horizontally. Doing so will provide symmetry between the items, as seen in the screenshot above. This step is a simple matter of setting the TreeView's ItemsPanel property to a Grid whose HorizontalAlignment is set to 'Center'. Let's take a look at the XAML for a Window which contains our customized TreeView:

<Window x:Class="CustomTreeViewLayout.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:CustomTreeViewLayout"
    Title="Custom TreeView" Height="350" Width="780"
    Loaded="OnLoaded"
    WindowStartupLocation="CenterScreen"
    FontSize="11"
    >
  <TreeView Name="tree">
    <TreeView.Resources>
      <ResourceDictionary>
        <!-- Import the resource dictionary file which
             contains the Style that makes TreeViewItems
             display their child items in an organization
             chart layout. -->
        <ResourceDictionary.MergedDictionaries>
          <ResourceDictionary Source="OrgChartTreeViewItemStyle.xaml" />
        </ResourceDictionary.MergedDictionaries>

        <!-- This template explains how to render
             a Node object and its child nodes. -->
        <HierarchicalDataTemplate
          DataType="{x:Type local:Node}"
          ItemsSource="{Binding ChildNodes}"
          >
          <TextBlock Text="{Binding Text}" />
        </HierarchicalDataTemplate>
      </ResourceDictionary>
    </TreeView.Resources>

    <!-- Put the root item(s) in a centered Grid so that
         they will be centered and retain their width. -->
    <TreeView.ItemsPanel>
      <ItemsPanelTemplate>
        <Grid
          HorizontalAlignment="Center"
          IsItemsHost="True" />
      </ItemsPanelTemplate>
    </TreeView.ItemsPanel>
  </TreeView>
</Window>

I am not going to discuss the code which populates the TreeView with dummy data. Feel free to peruse that code (and all the rest of it) in the source code download, which is available at the top of this article.

Tip

Customizing the ControlTemplate for the TreeViewItem class was easy once I discovered a little trick. I serialized the default TreeViewItem control template to XAML and then modified that until I got the result I was looking for.

The Big Bummer

Unfortunately there is no supported way to programmatically set the selected item in a TreeView. The TreeView's SelectedItem property does not have a setter. As a result, I could not customize the keyboard navigation for the TreeView. The demo project prevents the TreeView from responding to keyboard input altogether. If you enable keyboard navigation in the demo you will find that it is very unintuitive to navigate the items. Hopefully one day there will be a way to customize the keyboard navigation of a TreeView, but until then...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Josh Smith
Software Developer (Senior) Cynergy Systems
United States United States
Member
Josh creates software, for iOS and Windows.
 
He works at Cynergy Systems as a Senior Experience Developer.
 
Read his iOS Programming for .NET Developers[^] book to learn how to write iPhone and iPad apps by leveraging your existing .NET skills.
 
Use his Master WPF[^] app on your iPhone to sharpen your WPF skills on the go.
 
Check out his Advanced MVVM[^] book.
 
Visit his WPF blog[^] or stop by his iOS blog[^].

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionApply Same Style while Binding Treeview to Dataset [modified]memberdeeps107018 Mar '13 - 8:08 
Hi Josh,
Thank you for writing nice articles on wpf controls. I found your styles (OrgChartTreeViewItemStyle.xaml) are apt for my project and trying to apply to my treeview. But couldn't get through.... Please note my code snippet below....
 
Table Comp_Master
Comp_ID PARENT_ID COMP_NAME
1 NULL Root Comp
2 1 Test Comp 2- Under root
3 2 Child Comp 3 - Under Test Comp 2
4 2 Child Comp 4 - Under Test Comp 2
5 3 Child Comp 5 - Under Child Comp 3
 
Companyview.xaml.cs
 
namespace TimeLogWPF
{
///
/// Interaction logic for CompanyView.xaml
///

public partial class CompanyView : Window
{
cDataTier CDtier = new cDataTier();
//SqlDataReader RdrCommon = new SqlDataReader();
DataSet dsCommon = new DataSet();
 
public CompanyView()
{
InitializeComponent();
CDtier.dbConnect();
dsCommon = CDtier.ReturnDataSet("SELECT comp_name,comp_id,parent_id from COMP_MASTER");
dsCommon.Relations.Add("rsParentChild",
dsCommon.Tables[0].Columns["comp_id"],
dsCommon.Tables[0].Columns["Parent_ID"]);
DataView vwCompany = dsCommon.Tables[0].DefaultView;
vwCompany.RowFilter = "parent_ID is NULL";
trvCompany.DataContext = vwCompany;
}
 
private void button1_Click(object sender, RoutedEventArgs e)
{
var newForm = new TestForm();
newForm.Show();
}
}
}
 
Companyview.xaml.cs
 
<!-- I WANT THE OrgChartTreeViewItemStyle.xaml TO BE APPLIED ON THE BELOW TREEVIEW -->
TreeView Height="295" HorizontalAlignment="Left" Margin="56,25,0,0" Name="trvCompany" VerticalAlignment="Top" Width="406" ItemsSource="{Binding}"
TreeView.ItemTemplate
HierarchicalDataTemplate ItemsSource="{Binding Path=rsParentChild}"
TextBlock Text="{Binding Path=comp_name}"
HierarchicalDataTemplate
TreeView.ItemTemplate
TreeView
<Button Content="Button" Height="23" Name="button1" Width="75" Click="button1_Click" />

modified 18 Mar '13 - 14:19.

QuestionExpand children on clickmemberLuigi Saggese6 Nov '12 - 0:54 
It's possible to expand children on parent click?
Questionhow can i draw line between the rectangles ?memberpouyan momeny22 Jan '12 - 22:20 
I want to use your code to build up a organization chart but I need some changes
 
1- I need to draw lines between rectangles
2 - I don't want the root level node to be expanded this size. I want that I of my rectangles to be the same size. I did not see any code in your style that set the width of the nodes.
 
if you don't mind to help me plz send this code to pooyan.m@gmail.com
QuestionDrag and DropmemberMember 248296826 Sep '11 - 20:44 
Any idea how we can implement drag and drop for this?
Eg. Drag something from a listview to this styled tree view?
QuestionTemplating a potentially infinite TreeViewmemberÁkos György Pfeff14 Mar '11 - 8:00 
Hi Josh,
Thank you very much for all of your publications!
 
My problem is that I have a potentially infinite TreeView, as its ItemsSource contains elements, that can contain elements, and all of it can contain circles. So its a directed graph. My original goal was to create an upside-down-ish treeview template, so I used your TreeViewItem style without the ItemsPanel property setter.
Now, when the ItemsSource is set, the GUI thread works until I get a StackOverflowException. It worked fine with the original template.
Note:
I use some kind of MVVM, and my Model layer is an EF4 model.
 
Do you have any idea?
 
Thanks!
GeneralSerialization of Default ControlTemplatemembergilles211 Feb '11 - 0:14 
Hello,
 
Thank you for that great article.
I just wonder if you could tell us how to serialize
the default controlTemplate of the TreeViewItem ?
 
Thank´s
Gilles
GeneralHi Joshmemberhovhannisyankaren11 Sep '10 - 8:43 
Very nice article, Thank you very much.
Is there any possibility to customize WPF TreeView to have many parents for a child?
In ny words, can I make TreeView like graph.
GeneralRe: Hi JoshmvpJosh Smith11 Sep '10 - 14:53 
hovhannisyankaren wrote:
can I make TreeView like graph.

 
No, that's not possible to accomplish with the TreeView. You could render lines between a child and multiple "parents" but in terms of the TreeView/TreeViewItem object model, each node has one and only one parent node.
:josh:
Advanced MVVM[^]
Advance your MVVM skills

GeneralRe: Hi Joshmemberhovhannisyankaren15 Sep '10 - 8:46 
OK, thanks.
QuestionHow to display connecting lines along with node?memberViji Raj5 Mar '10 - 20:36 
Hi,
 
Can you tell me how to display connecting lines in the organization chart?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 24 Jan 2007
Article Copyright 2007 by Josh Smith
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid