---
# System prepended metadata

title: '`WinUI 3` VisualTreeから指定した型の要素を再帰的に取得する 2022-11-29'
tags: [WinUI 3, VisualTreeHelper, 再帰]

---

---
lang: ja-jp
breaks: true
---
# `WinUI 3` VisualTreeから指定した型の要素を再帰的に取得する 2022-11-29

```csharp=
    public static T? GetChildItem<T>(
        DependencyObject startElement
        )
        where T : DependencyObject
    {
        Type targetType = typeof(T);

        DependencyObject? result = startElement;

        int childrenCount = VisualTreeHelper.GetChildrenCount(startElement);
        int childIndex = -1;

        while (result?.GetType().Equals(targetType) == false)
        {
            childIndex++;
            if (childIndex >= childrenCount)
            {
                return null;
            }

            result = VisualTreeHelper.GetChild(startElement, childIndex);
            if (result == null)
            {
                return null;
            }

            DependencyObject? resultChild = GetChildItem<T>(result);
            if (resultChild != null)
            {
                return (T?)(object?)resultChild;
            }
        }

        return (T?)(object?)result;
    }
```


###### tags: `WinUI 3` `VisualTreeHelper` `再帰`
