Find child control from a parent control using type and name. Method will return null if no control is found.
Usage:
Window mainWindow = new Window(); TextBlock testTb = mainWindow.FindChild<TextBlock>("testTextBlock");
Code:
using System.Windows; using System.Windows.Media; public static class FindChildControlFromParent { public static T FindChild<T>(this DependencyObject parent, string childName) where T : DependencyObject { if (parent == null) return null; T foundChild = null; int childrenCount = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < childrenCount; i++) { var child = VisualTreeHelper.GetChild(parent, i); T childType = child as T; if (childType == null) { foundChild = FindChild<T>(child, childName); if (foundChild != null) break; } else if (!string.IsNullOrEmpty(childName)) { var frameworkElement = child as FrameworkElement; if (frameworkElement != null && frameworkElement.Name == childName) { foundChild = (T)child; break; } } else { foundChild = (T)child; break; } } return foundChild; } }