wpf 按名称查找控制的父级

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15198104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:50:16  来源:igfitidea点击:

Find Parent of Control by Name

wpfcontrolsparent

提问by user2025830

Is there a way to find the parents of a WPF control by its name, when the name is set in the xaml code?

当名称在 xaml 代码中设置时,是否可以通过名称查找 WPF 控件的父级?

回答by Arun Selva Kumar

Try this,

尝试这个,

element = VisualTreeHelper.GetParent(element) as UIElement;   

Where, element being the Children - Whose Parent you need to get.

哪里,元素是孩子 - 你需要得到谁的父母。

回答by Marc

In code, you can use the VisualTreeHelperto walk through the visual tree of a control. You can identify the control by its name from codebehind as usual.

在代码中,您可以使用VisualTreeHelper遍历控件的可视化树。您可以像往常一样通过代码隐藏中的名称识别控件。

If you want to use it from XAML directly, I would try implementing a custom 'value converter', which you could implement to find a parent control which meets your requirements, for example has a certain type.

如果你想直接从 XAML 使用它,我会尝试实现一个自定义的“值转换器”,你可以实现它来找到满足你要求的父控件,例如具有某种类型。

If you don't want to use a value converter, because it is not a 'real' conversion operation, you could implement a 'ParentSearcher' class as a dependency object, that provides dependency properties for the 'input control', your search predicate and the output control(s) and use this in XAML.

如果您不想使用值转换器,因为它不是“真正的”转换操作,您可以实现一个“ParentSearcher”类作为依赖对象,它为“输入控件”提供依赖属性,您的搜索谓词和输出控件并在 XAML 中使用它。

Does this help?

这有帮助吗?

回答by ScottyMacDev

Actually I was able to do this by recursively looking for the Parent control by name and type using the VisualTreeHelper.

实际上,我能够通过使用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;
    }