Pages

Men

rh

7/21/2012

The Logical Tree VS The Visual Tree in WPF

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.<br
 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);

 

No comments :

Post a Comment