views:

760

answers:

1

I'm looking for a reliable method to build a list of controls of <Type> contained in a specific <Panel> derived control - this includes those that are direct children, and those which are children of children and so on.

The most obvious way was to just do it recursively:
Add to list any children of this control of <Type>, then repeat function for any child of this control which is a <Panel> or descendant.

However I'm concerned that this won't find all controls in the tree - any ContentControl could also contain of a control of <Type>, as could HeaderedContentControl or any other similar control with one or more child/content attributes.

Is there any means of executing a search against the actual layout tree, so that any instance of a specific type of control contained without a specific parent can be found?

+5  A: 

Here is a fairly naive extension method:-

public static class VisualTreeEnumeration
{
   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;
     }
   }
}

This approach does have the draw back that it assumes no changes happen in the tree membership while its in progress. This could be mitigated in use by using a ToList().

Now you can effect your requirements using LINQ:-

 var qryAllButtons = myPanel.Descendents().OfType<Button>();
AnthonyWJones
Simple but useful extension method!
Todd