遞迴查詢子元素

celestially98發表於2024-05-08
private UIElement FindElementByNameInternal(DependencyObject parent, string name)
{
    if (parent == null || string.IsNullOrEmpty(name))
        return null;

    // 檢查當前元素是否為目標元素
    if (parent is FrameworkElement frameworkElement && frameworkElement.Name == name)
        return (UIElement)parent;

    // 遍歷當前元素的子元素
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        UIElement child = VisualTreeHelper.GetChild(parent, i) as UIElement;
        if (child != null)
        {
            // 遞迴查詢子樹中的元素
            UIElement foundElement = FindElementByNameInternal(child, name);
            if (foundElement != null)
                return foundElement;
        }
    }

    return null; // 如果未找到,返回null
}

相關文章