I need to search a WPF control hierarchy for controls that match a given name or type. How can I do this?
I have a sequence function like this (which is completely general):
public static IEnumerable SelectAllRecursively(this IEnumerable items, Func> func)
{
return (items ?? Enumerable.Empty()).SelectMany(o => new[] { o }.Concat(SelectAllRecursively(func(o), func)));
}
Getting immediate children:
public static IEnumerable FindChildren(this DependencyObject obj)
{
return Enumerable.Range(0, VisualTreeHelper.GetChildrenCount(obj))
.Select(i => VisualTreeHelper.GetChild(obj, i));
}
Finding all children down the hiararchical tree:
public static IEnumerable FindAllChildren(this DependencyObject obj)
{
return obj.FindChildren().SelectAllRecursively(o => o.FindChildren());
}
You can call this on the Window to get all controls.
After you have the collection, you can use LINQ (i.e. OfType, Where).