Blue Theme Orange Theme Green Theme Red Theme
 
World Class ASP.NET Hosting – Click Here for 3 Months Free/NO Setup Fee!
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » WPF » TreeView in WPF

TreeView in WPF

This tutorial shows you how to create and use a TreeView control available in WPF and XAML.

Author Rank:
Total page views :  81797
Total downloads :  929
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WPF TreeViewTutorial.zip
 
Become a Sponsor


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.

 

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.

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.

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.

 

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.

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.

 

 

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

 About the author
 
Mahesh Chand
Mahesh is a software developer with over 13 years of experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle. If you are looking for a Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WPF TreeViewTutorial.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
treeview by steeve On October 21, 2008
good tutorial.thanck you Mahesh.
Reply | Email | Delete | Modify | 
add image and check box for a new item by Sebastian On November 28, 2008
nice tutorial. could you provide please also support to add image and check box for any new item when user press button1_Click? Thank you, Sebi.
Reply | Email | Delete | Modify | 
Re: add image and check box for a new item by Mahesh On April 3, 2009
What you need to do is, create a TreeView item and add images and checkboxes to it, similar to in the code and Add it to the TreeView in code.
Reply | Email | Delete | Modify | 
Nice to see an example that works! by James On February 11, 2009
Thank you! There are so many dead end examples concerning the "Treeview" control.
Reply | Email | Delete | Modify | 
fantastic by Vikas On February 27, 2009
tried to cover most of the cases with treeview. Good One!
Reply | Email | Delete | Modify | 
c# implementation by Michael On July 29, 2009
Great article, however is it possible to implement the controls in the header dynamically, i.e. from the c#? At the moment i'm creating the TreeViewItems like this:

TreeViewItem newItem = new TreeViewItem();
newItem.Header = reflectionnodeclass.Name;
newItem.Focusable = false;
tvDataStructure.Items.Add(newItem);


Can I add the stackbox and checkbox controls to it as well from the c#?
Thanks!
Reply | Email | Delete | Modify | 
answered my own question by Michael On July 29, 2009
for reference, what i've done is

private StackPanel CreateHeader(string name, double min, double max)
        {
            StackPanel sp = new StackPanel();
            sp.Orientation = Orientation.Horizontal;
            sp.Margin = new Thickness(0, 0, 0, 0);

            Label lbl = new Label();
            lbl.Content = name;
            sp.Children.Add(lbl);

            Slider sld = new Slider();
            sld.Name = "sld" + name;
            sld.Width = 100;
            sld.Minimum = min;
            sld.Maximum = max;
            sld.Value = (min + max) / 2;
            sp.Children.Add(sld);
            return sp;
        }
Reply | Email | Delete | Modify | 
Issue with Underscore by Hemant On September 2, 2009
Hi,

i am having one issue if i have name as my_test

In Tree View i see text as mytest



Reply | Email | Delete | Modify | 
Re: Issue with Underscore by Mahesh On September 27, 2009
Try using "&_" and see if it works. Let us know.
Reply | Email | Delete | Modify | 
Problem with checkbox in treeview using VB.NET by naveen On December 7, 2009
Hi,
I need to select many checkboxes in a Tree view,
which are retrived from Database.

My project is windows based and using WPf.

Can anyone help on this issue ???

Kindly guide me for adding post and
viewing responses for that post from homepage

Thanks in advance

Regards

naveen...
Reply | Email | Delete | Modify | 
How can I get information in selectedItem by Cuong On September 28, 2009
Dear sir,
Thank for your code.
I want to known, how can I get information in item, which I selected?
Reply | Email | Delete | Modify | 
Need Help in treeview by Senthil On December 8, 2009
I am in need to parse the check box checked treeviewnode. In my project user has to check the checkbox in treeview node, so I need to get what are all tree view nodes has been checked by user.
Reply | Email | Delete | Modify | 
How to move nodes between two TreeViews objects? by Christopher On February 2, 2010
I have two treeview objects on my form. The first one contains parent and children nodes like the following:

Home
|---cHome
Login
|---cLogin
Billing
|
---cBilling1
---cBilling2
---cBilling3
|
Water
----cWater

If the user clicks on a parent node then clicks the "Add >" button, I want to move the selected parent and his children from the first treeview to the second treeview.

If the user clicks on a child node then clicks the "Add >" button, I want to move the selected child and any children from the first treeview to the second treeview.

How can I easily code this?
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.