View logic tree:
Note:
There is a hierarchical relationship between the elements of the WPF user interface, which is calledLogic tree. An element template can contain multiple elements, which are calledView tree. The gap between the two trees of WPF lies in the fact that you only need the logic tree for some problems.
<Window> <Grid> <Label Content="Label" /> <Button Content="Button" /> </Grid></Window>
Why do we need two different trees:
The WPF control consists of multiple primitive controls. For example, a button is composed of a border, a rectangle, and content. They should be view child controls of buttons. When WPF wants to display a button, the element itself will not be displayed, but it will traverse its view tree to display its child elements. This hierarchical relationship can also be used for hit testing and layout.
However, sometimes you do not pay attention to the border and shape of the control template. This is mainly because the template will be replaced at runtime, so you do not need to involve the structure of the view tree. You will need a richer tree that contains real controls, not the template part. This is the performance of the logic tree.
Logic tree:
Logic treeDescribes the relationship between user interface elements. It is mainly responsible:
- Inherit the value of dependency attribute
- Set dynamic resource reference
- Name of the bound query Element
- Route event Transfer
View tree:
View treeIncludes all view elements in the template of each logical element. It is responsible:
- Show view Elements
- Sets the transparency of elements.
- Set element layout and rendering changes
- Sets the isenable attribute of an element.
- Perform a hit Test
- Associated resources (root searching)
Root code in the view tree:
If the child element in the user interface needs to access the data in the parent element, but you do not have many generations in the middle. The best solution is to traverse the entire tree until you find the elements of the desired type.
This is a relatively accurate help program that you can find without having to modify anywhere.
Code
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 demonstrates how to use the help program. It starts from this until the elements of the grid type are located. If the root element of the tree is not found, null is returned.
var grid = VisualTreeHelperExtensions.FindAncestor<Grid>(this);