views:

33

answers:

1

Does anybody have a good way of finding ALL the controls within an object that is of the same type? Here's my scenario, I have a tab control and within each tab control exists a user control (ALL of which match the same base type e.g. MyBaseClassControl). I want to be able to find that user control WITHOUT having to use the control.FindName("controlName") method, rather I would like to get a handle on the control by type (e.g. base class). The VisualTreeHelper class seems to do nothing for me as it only returns native Silverlight objects.

A: 

Given this:

public static IEnumerable<DependencyObject> AllChildren(this DependencyObject root)
{
    var children = root.DirectChildren().ToList();
    return children.Union(children.SelectMany(o => o.AllChildren()));
}

public static IEnumerable<DependencyObject> DirectChildren(this DependencyObject parent)
{
    var childCount = VisualTreeHelper.GetChildrenCount(parent);
    for (var i = 0; i < childCount; i++)
        yield return System.Windows.Media.VisualTreeHelper.GetChild(parent, i);
}

You could do this:

myObj.AllChildren().OfType<MyBaseClassControl>();
PL
Oddly enough this extension method never return my custom base type. Is the "GetChildren" methods in the VisualTreeHelper recursive? I forgot to mention that the control I am looking for is contained in a Grid.
Should work although seriously inefficient. `Union` needs to track objects are not included more than once in the output which in this case is unecessary, children are placed are placed in a `List<T>` (also unnecessary) and all of this is done recursively which on a deeply nested object tree grows the cost of all of this massively.
AnthonyWJones
Agreed, if performance becomes the issue this can and should be optimized. For the purpose of the question - e.g. how to find a control by type - this does demonstrate it though.
PL