Bookmark and Share Share...    Subscribe to this feed Feed   About Christian Moser  


Logical- and Visual Tree

Introduction

Elements of a WPF user interface are hierarchically related. This relation is called the LogicalTree. The template of one element consists of multiple visual elements. This tree is called the VisualTree. WPF differs between those two trees, because for some problems you only need the logical elements and for other problems you want all elements.

 
<Window>
    <Grid>
        <Label Content="Label" />
        <Button Content="Button" />
    </Grid>
</Window>
 
 

Why do we need two different kind of trees?

A WPF control consists of multiple, more primitive controls. A button - for example - consists of a border, a rectangle and a content presenter. These controls are visual children of the button.
When WPF renders the button, the element itself has no appearance, but it iterates through the visual tree and renders the visual children of it. This hierarchical relation can also be used to do hit-testing, layout etc.
But sometimes you are not interested in the borders and rectangles of a controls' template. Particulary because the template can be replaced, and so you should not relate on the visual tree structure! Because of that you want a more robust tree that only contains the "real" controls - and not all the template parts. And that is the eligibility for the logical tree.

The Logical Tree

The logical tree describes the relations between elements of the user interface. The logical tree is responsible for:

  • Inherit DependencyProperty values
  • Resolving DynamicResources references
  • Looking up element names for bindings
  • Forwaring RoutedEvents

The Visual Tree

The visual tree contains all logical elements including all visual elements of the template of each element. The visual tree is responsible for:
  • Rendering visual elements
  • Propagate element opacity
  • Propagate Layout- and RenderTransforms
  • Propagate the IsEnabled property.
  • Do Hit-Testing
  • RelativeSource (FindAncestor)

Programmatically Find an Ancestor in the Visual Tree

If you are a child element of a user interface and you want to access data from a parent element, but you don't know how many levels up that elemens is, it's the best solution to navigate up the tree until it finds an element of the requested type.

This helper does excactly this. You can use almost the same code to navigate through the logical tree.

 
public static class VisualTreeHelperExtensions
{
    public static T FindAncestor<T>(DependencyObject dependencyObject)
        where T : class
    {
        DependencyObject target = dependencyObject;
        do
        {
            target = VisualTreeHelper.GetParent(target);
        }
        while (target != null && !(target is T));
        return target as T;
    }
}
 
 

The following example shows how to use the helper. It starts at this and navigates up the visual tree until it finds an element of type Grid. If the helper reaches the root element of the tree, it returns null.

 
var grid = VisualTreeHelperExtensions.FindAncestor<Grid>(this);
 
 




Last modified: 2010-06-29 08:34:41
Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments
Yathish
Commented on 5.December 2010
I found it useful. Thank you Christian!
blueskin
Commented on 6.December 2010
I am QT programmer for the past 3 years and this tutorial does give a me a basic understanding. But am still trying to understand the hierarchical relation in terms of OO programming concepts. If have a link that provides understanding on how these trees work that'd be great. I prefer understanding the lower level concepts rather than remembering them. Thank you.
Karthick
Commented on 19.January 2011
Nice article
prabhu
Commented on 10.February 2011
nice article. Good for beginners.

THANK YOU....
Janynne Gomes
Commented on 14.February 2011
Awesome explanation. Helped me a lot!

Tnx!
Dennis
Commented on 17.February 2011
Hey, I'm a beginner and really appreciate your efforts. Thank you. Some day this may seem old hat, but for now, it's all new to me. Thanks again and know your efforts are appreciated.
spencer
Commented on 22.February 2011
Really Nice Article for Beginners. Thanks for this helpful article . Thank you guys..
nightrider
Commented on 23.February 2011
good one for beginner
Amogh
Commented on 23.February 2011
You have explained things in all your articles in a very nice way. MSDN has got all of this but their way of explaining is mechanical and lot difficult and time consuming to understand.
Thanks for this stuff bro, it helps understand things quickly.
Mohamed...
Commented on 15.March 2011
Hi Im new to WPF and this article reaaly helps me alot....Its easy to understand and guide is given properly .Thnx dude.....Keep it up
Ratkiia
Commented on 20.March 2011
Very nice article and nicely explained.
Amihai
Commented on 21.March 2011
wonderful article
Sanjay Patolia
Commented on 24.March 2011
It was good but still it needed few practicle examples to elaborate Visual Trees
Simon
Commented on 2.April 2011
7 years ago I have felt that .design file in the classic C# is a worst practice of
design. For a number of projects I've developed and XML based mechanism of controls layout is universal for C#, MFC and run time visual object builders. Microsoft in Hertzlya(Israel ) sent us to...
XAML is like we have done, but does not suppose distribution of C# objects in assemblies and their dynamic link.What is about the example it could be done simple more if using XPATH and its reflection in tree of objects.
madhav
Commented on 28.April 2011
chengila
mangesh joshi
Commented on 7.May 2011
very very nice &amp; simple....
Con
Commented on 8.June 2011
Funny how I found your site (I mean the way i searched through the net). I've spent more than half of the day looking for tutorials in wpf. Thanks, this really helped me a lot in my school project. By the way I'm a Computer Science student and i wish to build some site like this someday. Thank you again!
Vivek...
Commented on 26.June 2011
Thanks for your great work..for me the following explanation is more clear

The Logical Tree is a tree structure that represents the hierarchy of controls and elements that constitute a piece of user interface in WPF, but without their inner parts.

For example, if a DockPanel contains a ListBox which contains a list of Buttons, the Logical Tree will consist of the following:

DockPanel
+ListBox
+Button
+Button
+Button


The Visual Tree is a tree structure that represents the fine-grained hierarchy of Visuals that constitute what appears on the screen. It contains the same elements as the Logical Tree, but includes all the Visuals that are used to compose the Logical Tree's controls and elements, like the ControlTemplates and DataTemplates.

The Visual Tree of the previous example would therefore be as follows:

DockPanel
+ListBox
+Border
+...
+VirtualizingStackPanel
+ListBoxItem
+Button
+Border
+....
Marcus Galka
Commented on 30.June 2011
Hallo Herr Mosers, vielen Dank f&Atilde;&frac14;r Ihre tolle Arbeit bei den Tutorials. Sehr gut gemacht und sehr verst&Atilde;&curren;ndlich. Hat mir sehr geholfen.
Rajshekar...
Commented on 5.July 2011
This is very good article and explained in simple words and realy very good for beginners
Alexander
Commented on 7.August 2011
Good expanation and easy to understand. I liked it.
Ravi Kurapati
Commented on 13.August 2011
Thanks bro... you made my day :) please continue your good work....
Girish
Commented on 16.September 2011
Thanks a lot..! :)
ghiwany
Commented on 17.September 2011
your example ist very simple to understand
thanks for all
Ashish Dhyani
Commented on 19.September 2011
Nice one! But can u explain it step by step?

Name
E-Mail (optional)
Comment