Skip to main content

LayoutTreeHelper

  • 2 minutes to read

The LayoutTreeHelper is a helper class that provides utility methods for iterating through elements of visual and logical trees and searching nodes.

Retrieving object’s visual parents

For accessing the visual parents of an object that is placed in a visual or logical tree, the LayoutTreeHelper provides the LayoutTreeHelper.GetVisualParents function.

public static IEnumerable<DependencyObject> GetVisualParents(
    DependencyObject child, 
    DependencyObject stopNode = null
)

This function returns a LINQ compatible collection. It allows you to use the wide capabilities of LINQ methods to access the required nodes of the visual and logical trees.

For instance, to get a specific parent Grid, you can use the following code.

var obj  = LayoutTreeHelper.GetVisualParents(PART_Button as DependencyObject)
    .OfType<Grid>()
    .FirstOrDefault(x => x.Name == "PART_Grid");

Retrieving object’s visual children

For accessing the visual children of an object, the LayoutTreeHelper provides the LayoutTreeHelper.GetVisualChildren function.

public static IEnumerable<DependencyObject> GetVisualChildren(DependencyObject parent)

Similar to GetVisualParents, this function also returns a LINQ compatible collection. Thus, you can also use LINQ extension methods to obtain the required child nodes.

Below is a sample code snippet that illustrates how to obtain the child CheckBox named as PART_CheckBox by using the GetVisualChildren function.

var obj = LayoutTreeHelper.GetVisualChildren(PART_Grid as DependencyObject)
    .OfType<CheckBox>()
    .FirstOrDefault(x => x.Name == "PART_CheckBox");