miercuri, 12 mai 2010

[1][3][WPF]Visual Tree - Logical Tree

[1][3][WPF]Visual Tree - Logical Tree

Two element trees exist within a WPF application: the logical tree and the visual tree
  • The logical tree is the hierarchical structure containing the exact elements of your WPF application as defined either declaratively within a XAML file, or imperatively in code
    • The logical tree outlines the 1:1 mapping of the nested XAML elements declared in the code snippet to their appropriate classes in the WPF API.
    • The LogicalTreeHelper class provides methods such as GetChildren and GetParent for querying the tree object to extract a list of child collections of elements from the tree of object elements.
    • _buttonCtrl.FindName(“_textCtrl");
  • Visual Tree
    • For each element in the logical tree, additional elements may be created to represent visual aspects required by the element. The combination of application elements and the elements created for visualization support is known as the visual tree.
    • Not all logical tree nodes appear in the visual tree; only the elements that derive from System.Windows.Media.Visual or System.Windows.Media.Visual3D are included
  • You can access both the logical and visual trees from code
    • You can easily traverse both the logical and visual trees using the somewhat symmetrical System.Windows.LogicalTreeHelper and System.Windows.Media.VisualTreeHelper classes
  • LogicalTreeHelper.GetChildren(obj as DependencyObject)
  • OnContentRendered, which doesn’t get called until after layout occurs
  • Visual class contains three protected members (VisualParent, VisualChildrenCount, and GetVisualChild) for examining its visual parent and children.


Sample:

static void PrintLogicalTree(int i_depth, object i_object)
{
// Print the object with preceding spaces that represent its depth
Debug.WriteLine(new string(' ', i_depth) + i_object);
// Sometimes leaf nodes aren’t DependencyObjects (e.g. strings)
if (!(i_object is DependencyObject)) return;
// Recursive call for each logical child
foreach (object child in LogicalTreeHelper.GetChildren(i_object as DependencyObject))
{
PrintLogicalTree(i_depth + 1, child);
}
}

static void PrintVisualTree(int i_depth, DependencyObject i_obj)
{
// Print the object with preceding spaces that represent its depth
Debug.WriteLine(new string(' ', i_depth) + i_obj);
// Recursive call for each visual child
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(i_obj); i++)
{
PrintVisualTree(i_depth + 1, VisualTreeHelper.GetChild(i_obj, i));
}
}

Niciun comentariu:

Trimiteți un comentariu