I need to search a WPF control hierarchy for controls that match a given name or type. How can I do this?
I edited CrimsonX's code as it was not working with superclass types:
public static T FindChild(DependencyObject depObj, string childName)
where T : DependencyObject
{
// Confirm obj is valid.
if (depObj == null) return null;
// success case
if (depObj is T && ((FrameworkElement)depObj).Name == childName)
return depObj as T;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
//DFS
T obj = FindChild(child, childName);
if (obj != null)
return obj;
}
return null;
}