递归查找视觉子项是不是在 WPF 中添加根对象?

Find visual children recursively is not adding the root object in WPF?

我有以下实现来获取类型 T 的 VisualTree 中的所有子项:

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

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

我使用以下方法调用此方法:

IEnumerable<TextBlock> textBlocks = FindVisualChildren<TextBlock>(
    button.Content as DependencyObject);

但是,当根依赖对象的类型为 T 时,此实现无法正常工作。想象一下,我们想要在 VisualTree 中找到所有 TextBlocks

Content
  StackPanel
      TextBlock
      Image

在这种情况下,实现成功找到了 TextBlock。但是,如果我有其他布局:

Content
    TextBlock

该实现不包括根对象,因此未找到 TextBlock。如何重写方法并包含根对象?

我需要在循环之前产生 return 根。此实现进行修复:

    IEnumerable<T> FindVisualChildren<T>(DependencyObject dependencyObject) where T : DependencyObject
    {
        if (dependencyObject == null)
            yield break;

        if (dependencyObject is T)
            yield return (T)dependencyObject;

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(dependencyObject, i);
            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }