Posted by: Zeeshan Amjad | January 6, 2011

Traversing Visual Tree


WPF has two different concept called Visual Tree and Logical Tree. here we are going to see the Visual Tree. Visual tree describe how items are going to display on the screen. To better understand this, let’s take an example of simple command button. Button is in fact made by some simple controls. Such as ButtonChrome, which uses ContentPresenter that itself uses TextBlock. Similarly CheckBox is made by BulletDecorator, BulletChrome, ContentPresenter and TextBlock. Here we are going to traverse the Visual Tree and display it in TreeView. VisualTreeHelper class is used to traverse the visual tree. This class is inherited by Object and has lots of other useful methods other than traversing the visual tree.  Here is a class diagram of this class.

VisualTreeHelper

Traversing the Visual tree is very simple recursive call. Here is a recursive method to traverse visual tree and insert it into TreeView.

Code Snippet
  1. public void TraverseVisualTree(DependencyObject parent, TreeViewItem tvi)
  2. {
  3.     for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
  4.     {
  5.         var child = VisualTreeHelper.GetChild(parent, i);                
  6.  
  7.         TreeViewItem tviChild = new TreeViewItem();
  8.         tviChild.Header = child.GetType().ToString();
  9.  
  10.         if (tree.Items.Count == 0)
  11.         {
  12.             tree.Items.Add(tviChild);
  13.         }
  14.         else
  15.         {
  16.             tvi.Items.Add(tviChild);
  17.         }
  18.  
  19.         TraverseVisualTree(child, tviChild);
  20.     }            
  21. }

 

Here we check if the TreeView is empty or not. If tree view is empty, means it is first call of the method, then inserted information into tree view and for all the subsequent calls, insert information into tree view item

To make sure that all the tree is already expended, we define on style in resource section of our window.

Code Snippet
  1. <Window.Resources>
  2.     <Style TargetType="TreeViewItem">
  3.         <Setter Property="IsExpanded" Value="True" />
  4.     </Style>
  5. </Window.Resources>

 

Rest of the code if very easy. We just created one list box and inserted some items in it. After that we are going to see the Visual Tree of that list box when user press the “Display Visual Tree” button. Here is complete XAML code of this program.

Code Snippet
  1. <Window x:Class="WpfVisualTree.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
  4.         Title="Visual Tree" Height="600" Width="900">
  5.     <Window.Resources>
  6.         <Style TargetType="TreeViewItem">
  7.             <Setter Property="IsExpanded" Value="True" />
  8.         </Style>
  9.     </Window.Resources>
  10.     <Grid>
  11.         <Grid.RowDefinitions>
  12.             <RowDefinition Height="8*"/>
  13.             <RowDefinition/>
  14.         </Grid.RowDefinitions>
  15.         <Grid.ColumnDefinitions>
  16.             <ColumnDefinition/>
  17.             <ColumnDefinition/>
  18.         </Grid.ColumnDefinitions>
  19.         <TreeView Grid.Row="0" Grid.Column="0" Name="tree" Margin="5"/>
  20.         <ListBox Grid.Row="0" Grid.Column="1" Name="list" Margin="5">
  21.         </ListBox>
  22.         <Button Grid.Row="1" Grid.Column="0" Name="btnVisualTree" Margin="5" Click="btnVisualTree_Click">
  23.             Display Visual Tree
  24.         </Button>
  25.         <Button Grid.Row="1" Grid.Column="1" Name="btnExit" Margin="5" Click="btnExit_Click">
  26.             Exit
  27.         </Button>
  28.     </Grid>
  29. </Window>

 

Here is complete C# code of the program

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Data;
  8. using System.Windows.Documents;
  9. using System.Windows.Input;
  10. using System.Windows.Media;
  11. using System.Windows.Media.Imaging;
  12. using System.Windows.Navigation;
  13. using System.Windows.Shapes;
  14. using System.Windows.Media.Media3D;
  15.  
  16. namespace WpfVisualTree
  17. {
  18.     /// <summary>
  19.     /// Interaction logic for MainWindow.xaml
  20.     /// </summary>
  21.     public partial class MainWindow : Window
  22.     {
  23.         public MainWindow()
  24.         {
  25.             InitializeComponent();
  26.  
  27.             List<String> states = new List<string>();
  28.  
  29.             states.Add("California");
  30.             states.Add("Maryland");
  31.             states.Add("Washington");
  32.             states.Add("New York");
  33.             states.Add("Taxes");
  34.  
  35.             list.ItemsSource = states;
  36.         }
  37.  
  38.         public void TraverseVisualTree(DependencyObject parent, TreeViewItem tvi)
  39.         {
  40.             for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
  41.             {
  42.                 var child = VisualTreeHelper.GetChild(parent, i);                
  43.  
  44.                 TreeViewItem tviChild = new TreeViewItem();
  45.                 tviChild.Header = child.GetType().ToString();
  46.  
  47.                 if (tree.Items.Count == 0)
  48.                 {
  49.                     tree.Items.Add(tviChild);
  50.                 }
  51.                 else
  52.                 {
  53.                     tvi.Items.Add(tviChild);
  54.                 }
  55.  
  56.                 TraverseVisualTree(child, tviChild);
  57.             }            
  58.         }
  59.  
  60.         private void btnVisualTree_Click(object sender, RoutedEventArgs e)
  61.         {
  62.             TreeViewItem tvi = new TreeViewItem();
  63.             TraverseVisualTree(list, tvi);
  64.         }
  65.  
  66.         private void btnExit_Click(object sender, RoutedEventArgs e)
  67.         {
  68.             Close();
  69.         }
  70.     }
  71. }

 

Here is the output of the program when user clicks the “Display Visual Tree” button.

VisualTreeOutput

Advertisements

Responses

  1. Hey, you have a great blog here! I’m definitely going to bookmark you! I have a http://www.kuwait-h.com.

    • Thanks to like it.

  2. […] already saw one example of traversing visual tree here. But at that time we only display that information. We can do lot more than that and create very […]

  3. […] already saw couple of example of traversing visual tree here and here. But in both example we don’t care about the name of the control defined in XAML we only […]

  4. Very well done! Thank you!

    • Thanks.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: