Monday, September 26, 2011

How to get Visual Tree using VisualTreeHelper class in WPF?


You might be aware about Visual Tree and Logical Tree in WPF. If you are new to WPF and don’t know about visual tree and logical tree please go through my post on Visual Tree vs. Logical Tree first.

In this post I will demonstrate how to get Visual Tree using VisualTreeHelper class. VisualTreeHelper class is very useful class to navigate through element’s children. It provides some methods to get child element, to get parent element, total children etc. First let’s have a look on below code snippet.

<Window.Resources>
    <Style TargetType="TreeViewItem">
        <Setter Property="IsExpanded" Value="True" />
    </Style>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="0.2*" />
        <RowDefinition />
    </Grid.RowDefinitions>
    <TreeView Name="treeView" VerticalAlignment="Top"
                Grid.Row="1" HorizontalAlignment="Left"
                ScrollViewer.HorizontalScrollBarVisibility="Auto"
                ScrollViewer.VerticalScrollBarVisibility="Auto"
                Height="Auto" Width="Auto"/>
    <Button Name="getVisualTree" Content="Get Visual Tree"
            Height="35" Width="150"
            Click="getVisualTree_Click"/>
</Grid>

private void getVisualTree_Click(object sender, RoutedEventArgs e)
{
    treeView.Items.Clear();
    AddElementToTree(this, null);
}

public void AddElementToTree(DependencyObject parent, TreeViewItem treeViewItem)
{

    TreeViewItem newTreeViewItem = new TreeViewItem();

    newTreeViewItem.Header = parent.GetType().ToString();

    if (treeViewItem == null)
    {
        treeView.Items.Add(newTreeViewItem);
    }
    else
    {
        treeViewItem.Items.Add(newTreeViewItem);
    }

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        var childElement = VisualTreeHelper.GetChild(parent, i);
        AddElementToTree(childElement, newTreeViewItem);
    }
}



In above example, I have added one treeview control to XAML and set its TreeViewItem’s style to Expanded by default. I also added one Button named getVisualTree and its onclick event i am adding elements to treeview control.

AddElementToTree(this, null);

This method will retrieve visual tree of given dependency object. In our example i have provided ‘this’ as parent element. This will retrieve visual tree of Window. You can specify other elements if you want to retrieve specific element’s visual tree.

public void AddElementToTree(DependencyObject parent, TreeViewItem treeViewItem)
{

    TreeViewItem newTreeViewItem = new TreeViewItem();

    newTreeViewItem.Header = parent.GetType().ToString();

    if (treeViewItem == null)
    {
        treeView.Items.Add(newTreeViewItem);
    }
    else
    {
        treeViewItem.Items.Add(newTreeViewItem);
    }

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        var childElement = VisualTreeHelper.GetChild(parent, i);
        AddElementToTree(childElement, newTreeViewItem);
    }
}

This method takes two arguments first one is dependency object and another is treeview item. This method uses help of VisualTreeHelper class to get child.

VisualTreeHelper.GetChildrenCount(parent)

Above method returns total number of children of parent element. Below method return child element of parent at specified number.

VisualTreeHelper.GetChild(parent, i)

So the above for loop will get all the children of an element. This method is called recursively until all elements are added to the tree.


See also –

1 comment: