Find all controls in WPF Window by type

This should do the trick:

public static IEnumerable<T> FindVisualChilds<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj == null) yield return (T)Enumerable.Empty<T>();
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        DependencyObject ithChild = VisualTreeHelper.GetChild(depObj, i);
        if (ithChild == null) continue;
        if (ithChild is T t) yield return t;
        foreach (T childOfChild in FindVisualChilds<T>(ithChild)) yield return childOfChild;
    }
}

then you enumerate over the controls like so

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

This is the easiest way:

IEnumerable<myType> collection = control.Children.OfType<myType>(); 

where control is the root element of the window.

EDIT - As pointed out in the comments. This only goes one level deep. See the accepted answer for an option that goes deeper.

Tags:

C#

.Net

Wpf