ARTICLE

TreeView in WPF

Posted by Mahesh Chand Articles | WPF February 27, 2009
This tutorial shows you how to create and use a TreeView control available in WPF and XAML.
Reader Level:
Download Files:
 

Introduction

A TreeView represents data in a hierarchical view in a parent child relationship where a parent node can be expanded or collapse. The left side bar of Windows Explorer is an example of a TreeView.

 

The TreeView tag represents a WPF TreeView control in XAML.

 

<TreeView></TreeView>

 

The Width and Height properties represent the width and the height of a TreeView.  The Name property represents the name of the control, which is a unique identifier of a control. The Margin property tells the location of a TreeView on the parent control. The HorizontalAlignment and VerticalAlignment properties are used to set horizontal and vertical alignments.

 

The following code snippet sets the name, height, and width of a TreeView control.  The code also sets horizontal alignment to left and vertical alignment to top.

 

<TreeView Margin="10,10,0,13" Name="TreeView1" HorizontalAlignment="Left"

                 VerticalAlignment="Top" Width="194" Height="200" />

 

Adding TreeView Items

A TreeView control hosts a collection of TreeViewItem. The Header property is the text of the item that is displayed on the view. The following code snippet adds a parent item and six child items to a TreeView control.

<TreeView Margin="10,10,0,13" Name="TreeView1" HorizontalAlignment="Left"

 VerticalAlignment="Top" Width="194" Height="200">

    <TreeViewItem Header="Cold Drinks">

        <TreeViewItem Header="Coke"></TreeViewItem>

        <TreeViewItem Header="Pepsi"></TreeViewItem>

        <TreeViewItem Header="Orange Juice"></TreeViewItem>

        <TreeViewItem Header="Milk"></TreeViewItem>

        <TreeViewItem Header="Iced Tea"></TreeViewItem>

        <TreeViewItem Header="Mango Shake"></TreeViewItem>

    </TreeViewItem>

</TreeView>

By default, the parent node is collapsed but when you click on it, the expanded view looks like Figure 1.

 WPFTreeViewImg1.jpg

Figure 1. TreeView with items

Adding TreeView Items Dynamically

In previous section, we saw how to add items to a TreeView at design-time from XAML. We can add items to a TreeView from the code.  

Let's change our UI and add a TextBox and a button control to the page. The XAML code for the TextBox and Button controls look like following:

<TextBox Height="23" HorizontalAlignment="Left" Margin="8,14,0,0"

                 Name="textBox1" VerticalAlignment="Top" Width="127" />

<Button Height="23" Margin="140,14,0,0" Name="button1" VerticalAlignment="Top"

                HorizontalAlignment="Left" Width="76" Click="button1_Click">

            Add Item

</Button>

The final UI looks like Figure 2. On Add Item button click event handler, we are going to add a new item to the first parent node of the TreeView.

WPFTreeViewImg2.jpg

Figure 2.

On button click event handler, we add the content of TextBox to the TreeViewItem by calling TreeViewItem.Items.Add method. The following code adds TextBox contents to the TreeViewItem items.

private void button1_Click(object sender, RoutedEventArgs e)

{

    TreeViewItem newChild = new TreeViewItem();

    newChild.Header = textBox1.Text;

    Parent.Items.Add(newChild);

}

On button click event handler, we add the content of TextBox to the TreeView by calling TreeViewItem.Items.Add method.

Now if you enter text in the TextBox and click Add Item button, it will add contents of the TextBox to the TreeView.

WPFTreeViewImg3.jpg

Figure 3. Adding TreeView items dynamically

Deleting TreeView Items

We can use TreeView.Items.Remove or TreeView.Items.RemoveAt method to delete an item from the collection of items in the TreeView. The RemoveAt method takes the index of the item in the collection.

Now, we modify our application and add a new button called Delete Item. The XAML code for this button looks like below.

<Button Height="23" Margin="226,14,124,0" Name="DeleteButton"

        VerticalAlignment="Top" Click="DeleteButton_Click">

    Delete Item</Button>

The button click event handler looks like following. On this button click, we find the index of the selected item and call TreeView.Items.RemoveAt method as following.

 

private void DeleteButton_Click(object sender, RoutedEventArgs e)

{

   TreeView1.Items.RemoveAt

       (TreeView1.Items.IndexOf(TreeView1.SelectedItem));                 

}

The above code removes root items from the TreeView, not the subitems. To remove sub items, first we need to find the selected item and then we need to call TreeViewItem.Items.RemoveAt method.


 

Styling a TreeView Items

A TreeView control is placed inside a StackPanel that contains a ScrollVewer control so when the width of height of the panel is more than the visible area, the scroll viewer gets active and provides horizontal and vertical scrolling functionality.

To style a TreeView, we can use individual TreeViewItems and set their properties. Alternatively, we can use System.Resources and set Style property. The following code snippet sets TreeViewItem foreground, font size, and font weight properties.

<Window.Resources>

    <Style TargetType="{x:Type TreeViewItem}">

        <Setter Property="Foreground" Value="Blue"/>           

        <Setter Property="FontSize" Value="12"/>

        <Setter Property="FontWeight" Value="Bold" />

    </Style>

</Window.Resources>

The new TreeView looks like Figure 4.

WPFTreeViewImg4.jpg 

Figure 4. Formatted TreeView

Displaying Images in a TreeView

We can put any controls inside a TreeViewItem such as an image and text. To display an image side by side some text, I simply put an Image and TextBlock control within a StackPanel. The Image.Source property takes the name of the image you would like to display in the Image control and TextBlock.Text property takes a string that you would like to display in the TextBlock.

The following code snippet adds an image and text to a TreeViewItem. The key here is to add image and text to the header of TreeViewItems.

<TreeViewItem Name="Child1">

    <TreeViewItem.Header>

        <StackPanel Orientation="Horizontal">

            <Image Source="coffie.jpg" Height="30"></Image>

            <TextBlock Text="Coffie"></TextBlock>

        </StackPanel>

    </TreeViewItem.Header>

</TreeViewItem> 

After changing my code for all 5 TreeViewItems, the TreeView looks like Figure 5.

WPFTreeViewImg5.jpg

Figure 5.  TreeViewItems with Image and text

TreeView with CheckBoxes

If you put a CheckBox control inside TreeViewItems, you generate a TreeView control with checkboxes in it. The CheckBox can host controls within it as well. For instance, we can put an image and text block as content of a CheckBox.

The following code snippet adds a CheckBox with an image and text to a TreeViewItem.

<TreeViewItem Name="Child1">

    <TreeViewItem.Header>

        <CheckBox Name="CoffieCheckBox">

            <StackPanel Orientation="Horizontal">

            <Image Source="coffie.jpg" Height="30"></Image>

            <TextBlock Text="Coffie"></TextBlock>

        </StackPanel>

        </CheckBox>

    </TreeViewItem.Header>

</TreeViewItem>

 

I change the code of TreeViewItems and add following CheckBoxes to the items. As you may see, I have set the name of the CheckBoxes using Name property. If you need to access these CheckBoxes, you may access them in the code using their Name property.

  <TreeViewItem Name="Child1">

        <TreeViewItem.Header>

            <CheckBox Name="CoffieCheckBox">

                <StackPanel Orientation="Horizontal">

                    <Image Source="coffie.jpg" Height="30"></Image>

                    <TextBlock Text="Coffie"></TextBlock>

                </StackPanel>

            </CheckBox>

        </TreeViewItem.Header>

    </TreeViewItem>

    <TreeViewItem Name="Child2">

        <TreeViewItem.Header>

            <CheckBox Name="IcedTeaCheckBox">

                <StackPanel Orientation="Horizontal">

                    <Image Source="IcedTea.jpg" Height="30"></Image>

                    <TextBlock Text="Iced Tea"></TextBlock>

                </StackPanel>

            </CheckBox>

        </TreeViewItem.Header>

    </TreeViewItem>

    <TreeViewItem Name="Child3">

        <TreeViewItem.Header>

            <CheckBox Name="MangoShakeCheckBox">

                <StackPanel Orientation="Horizontal">

                <Image Source="MangoShake.jpg" Height="30"></Image>

                <TextBlock Text="Mango Shake"></TextBlock>

            </StackPanel>

            </CheckBox>

        </TreeViewItem.Header>

    </TreeViewItem>

    <TreeViewItem Name="Child4">

        <TreeViewItem.Header>

            <CheckBox Name="MilkCheckBox">

                <StackPanel Orientation="Horizontal">

                <Image Source="Milk.jpg" Height="30"></Image>

                <TextBlock Text="Milk"></TextBlock>

            </StackPanel>

            </CheckBox>

        </TreeViewItem.Header>

    </TreeViewItem>

    <TreeViewItem Name="Child5">

        <TreeViewItem.Header>

            <CheckBox Name="TeaCheckBox">

                <StackPanel Orientation="Horizontal">

                <Image Source="Tea.jpg" Height="30"></Image>

                <TextBlock Text="Tea"></TextBlock>

            </StackPanel>

            </CheckBox>

        </TreeViewItem.Header>

    </TreeViewItem>

    <TreeViewItem Name="Child6">

        <TreeViewItem.Header>

            <CheckBox Name="OrangeJuiceCheckBox">

                <StackPanel Orientation="Horizontal">

                <Image Source="OrangeJuice.jpg" Height="30"></Image>

                <TextBlock Text="Orange Juice"></TextBlock>

            </StackPanel>

            </CheckBox>

        </TreeViewItem.Header>

    </TreeViewItem>               

</TreeViewItem>

 

Now, the new TreeView looks like Figure 6.

 

WPFTreeViewImg6.jpg 

Figure 6. TreeView with CheckBoxes

Summary

This tutorial showed how to use a TreeView control in WPF and XAML. You also learned how to add check boxes and images to a TreeView items.

Login to add your contents and source code to this article
Article Extensions
Contents added by hans urschel on Jul 05, 2012
If you click the delete - button, you get an exception. The reason is, that the TreeView1.Items.IndexOf(TreeView1.SelectedItem) is -1 if you select an itme under "Cold Drink".You must use Parent.Items.IndexOf

Contents added by Sleepwisely on May 19, 2009

You can add subitems like that:

TreeViewItem
newChild = new TreeViewItem();
newChild.Header = "Item";
TreeView1.Items.Add(newChild);

TreeViewItem
newSubChild = new TreeViewItem();
newSubChild.Header = "SubItem";
newChild.Items.Add(newSubChild);

TreeViewItem
newSubSubChild = new TreeViewItem();
newSubSubChild.Header = "SubSubItem";
newSubChild.Items.Add(newSubSubChild);

Contents added by venu volla on May 18, 2009

Hi,

Ur Article --- "Treeview in WPF"  is really helpful.

I would be excellent if You discuss more like " How To ADD Child Items to The Child Items, i.e., the Second level of the treeview

+COOlDrinks
    Coke
    Pepsi
   +ThumsUp
      Sprite
      7up
      Mirinda
    
like this... Child items added to  " ThumsUp " Item... Can u do this...

Thank you, I would appreciate that

post comment
     

Hey Mahesh, thanks for the post. I want to display an XML document in a treeview, which I am able to do it, but I am not able to figure out how do I set the foreground color of treeview items based on certain values which are XML attributes.

Posted by yogesh sanghi Jul 06, 2012

To answer your second comment Amit, a code can be written in several different ways. Same applies to a problem. I can go home using 4 different road. It depends on what I choose. I may not choose the shortest or the fastest road. But you are most welcome to share your expertise and code. I am not saying this is the perfect article but what I am saying is, we would love to see some code samples from expert like yourself.

Posted by Mahesh Chand Jun 27, 2012

Amit, this article was written in 2009 when there was not too much information on TreeView. Now there is much more and people have learned more. This is for beginner only. I believe, you have passed that stage. We would love to see more complex articles/sample code if you don't mind sharing with us.Cheers!

Posted by Mahesh Chand Jun 27, 2012

your sample only adds one items to the tree at each event ... nothing new in that so i did not learn anything new in there. your delete is buggy and code bails out and crashes ... also what i was looking for was how to add child to a parent which I guess you have not done it so got your message "good luck with that" . the truth is this kind of coding in xaml is not a big deal and also won't be accepted since you better using mvvm which apparently you have not wpf is awesome and all that but less people know it and that is what i'm not enjoy it.

Posted by Amit Kohan Jun 27, 2012

I'm wondering why these kind of blogs are not complete. don't get me wrong I'm not saying it doesn't give you information but in fact it can be confusing for a newbie. These techniques are not advanced ones so it basically targets newbies like me. if you write the above xaml and then add the next block of xaml your page/form will be a mess. won't it be more helpful if author takes his time and explain step by step. this way this blog serving the knowledge of treeview rather art of debugging.again, let's say I'm wrong here but even using this drives compiler nuts ... it has no idea what "Items" is so as you see if you want to help and offer a complete article it is better to share the details yes even namespaces being used if not then at least few people are happy here and continue you work.Thanks for reading it.

Posted by Amit Kohan Jun 27, 2012
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter