Find all controls in WPF Window by type

Andrija picture Andrija · Jun 10, 2009 · Viewed 190.8k times · Source

I'm looking for a way to find all controls on Window by their type,

for example: find all TextBoxes, find all controls implementing specific interface etc.

Answer

Bryce Kahle picture Bryce Kahle · Jun 10, 2009

This should do the trick

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}

then you enumerate over the controls like so

foreach (TextBlock tb in FindVisualChildren<TextBlock>(window))
{
    // do something with tb here
}