Chris
Chris

Reputation: 2168

Get all logical children

I'm trying to get all of the logical children in my view (a user control). I start from the root element, and traverse the logical tree, and everything works as expected, however, several of my child controls are items like ListBox etc. that are data bound and use data templates for their children, and these are the items that are not getting returned in the logical tree.

Here is the code I am using:

private static void GetLogicalChildren<T>(DependencyObject parent, List<T> logicalCollection) where T : DependencyObject
    {
        IEnumerable children = LogicalTreeHelper.GetChildren(parent);

        foreach (object child in children)
        {
            if (child is DependencyObject)
            {
                DependencyObject depChild = child as DependencyObject;

                if (child is T)
                {
                    logicalCollection.Add(child as T);
                }

                GetLogicalChildren(depChild, logicalCollection);
            }
        }
    }

Upvotes: 1

Views: 3456

Answers (1)

Barracoder
Barracoder

Reputation: 3764

The controls rendered by DataTemplates are not in the logical tree, they're in the visual tree. The DataContext objects (Viewmodels probably) to which the DataTemplates are bound are in the logical tree in the Items property.

If you want to get the visual controls contained in child DataTemplates you need to look at the visual tree, not the logical tree.

VisualTreeHelper has a GetChild method and a ChildCount property that you can use to iterate through the visual children of your ItemsControls

Upvotes: 5

Related Questions