Find all controls in WPF Window by type

后端 未结 17 1271
春和景丽
春和景丽 2020-11-21 10:14

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 i

17条回答
  •  失恋的感觉
    2020-11-21 10:36

    This should do the trick

    public static IEnumerable FindVisualChildren(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(child))
                {
                    yield return childOfChild;
                }
            }
        }
    }
    

    then you enumerate over the controls like so

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

提交回复
热议问题