VisualTreeHelper.GetChild(DependencyObject, Int32) VisualTreeHelper.GetChild(DependencyObject, Int32) VisualTreeHelper.GetChild(DependencyObject, Int32) VisualTreeHelper.GetChild(DependencyObject, Int32) Method

Definition

Using the provided index, obtains a specific child object of the provided object by examining the visual tree.

public : static DependencyObject GetChild(DependencyObject reference, int childIndex)
static DependencyObject GetChild(DependencyObject reference, int32_t childIndex) const;
public static DependencyObject GetChild(DependencyObject reference, Int32 childIndex)
Public Shared Function GetChild(reference As DependencyObject, childIndex As Int32) As DependencyObject

Parameters

reference
DependencyObject DependencyObject

The object that holds the child collection.

childIndex
Int32 Int32

The index of the requested child object in the reference child collection.

Returns

The child object as referenced by childIndex.

Examples

Here's an example of a utility function that can copy a list of child elements of a particular type from within a visual tree. It uses the basic traversal methods GetChildrenCount and GetChild. It uses recursion so that elements can be found no matter what level of nesting within intermediate containers exists. It also uses an IsSubclassOf extension method from System.Reflection that extends the type comparison to consider subtypes as a match for a Type.

internal static void FindChildren<T>(List<T> results, DependencyObject startNode)
  where T : DependencyObject
{
    int count = VisualTreeHelper.GetChildrenCount(startNode);
    for (int i = 0; i < count; i++)
    {
        DependencyObject current = VisualTreeHelper.GetChild(startNode, i);
        if ((current.GetType()).Equals(typeof(T)) || (current.GetType().GetTypeInfo().IsSubclassOf(typeof(T))))
        {
            T asType = (T)current;
            results.Add(asType);
        }
        FindChildren<T>(results, current);
    }
}