按名称查找控件的父级

14

当WPF控件的名称在xaml代码中设置时,是否有一种方法可以通过其名称找到其父级控件?

3个回答

9
尝试这个:
element = VisualTreeHelper.GetParent(element) as UIElement;   

在这里,“element”指的是需要获取父元素的子元素。


9

实际上,我能够通过使用VisualTreeHelper递归查找父控件的名称和类型来实现此操作。

    /// <summary>
    /// Recursively finds the specified named parent in a control hierarchy
    /// </summary>
    /// <typeparam name="T">The type of the targeted Find</typeparam>
    /// <param name="child">The child control to start with</param>
    /// <param name="parentName">The name of the parent to find</param>
    /// <returns></returns>
    private static T FindParent<T>(DependencyObject child, string parentName)
        where T : DependencyObject
    {
        if (child == null) return null;

        T foundParent = null;
        var currentParent = VisualTreeHelper.GetParent(child);

        do
        {
            var frameworkElement = currentParent as FrameworkElement;
            if(frameworkElement.Name == parentName && frameworkElement is T)
            {
                foundParent = (T) currentParent;
                break;
            }

            currentParent = VisualTreeHelper.GetParent(currentParent);

        } while (currentParent != null);

        return foundParent;
    }

2
在代码中,您可以使用VisualTreeHelper来遍历控件的可视树。您可以像通常一样通过其名称从代码后台识别控件。
如果您想直接从XAML中使用它,我建议尝试实现一个自定义的“值转换器”,您可以实现它来查找符合您要求的父控件,例如具有特定类型的控件。
如果您不想使用值转换器,因为它不是一个“真正”的转换操作,您可以将“ParentSearcher”类作为依赖对象实现,为“输入控件”、搜索谓词和输出控件提供依赖属性,并在XAML中使用它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接