Tuesday 2 April 2013

Silverlight: get children of a control

Question:
How to get in Silverlight all children of a given control?
Get all children of a given type from a control in Silverlight 4?


Answer:
You use the helper class VisualTreehelper

The following extension method gets all children of a certain type recursively.
public static IEnumerable<T> GetChildrenRecursive<T>(this DependencyObject elm) where T : DependencyObject
{
    var childrenCount = VisualTreeHelper.GetChildrenCount(elm);

    for (int i = 0; i < childrenCount; i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(elm, i);
        if (child is T)
        {
            yield return (child as T);
        }

        else
        {
            foreach (var children in GetChildrenRecursive<T>(child))
            {
                yield return children;
            }
        }
    }
}


The following extension method gets all children of any DependencyObject in Silverlight, recursively.

public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
{
    int count = VisualTreeHelper.GetChildrenCount(root);
    for (int i = 0; i < count; i++)
    {
        var child = VisualTreeHelper.GetChild(root, i);
        yield return child;
        foreach (var descendent in Descendents(child))
            yield return descendent;
    }
}

No comments: