Find Parent of Control by Name

一个人想着一个人 提交于 2020-03-01 01:39:28

问题


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


回答1:


Try this,

element = VisualTreeHelper.GetParent(element) as UIElement;   

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




回答2:


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

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.

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.

Does this help?




回答3:


Actually I was able to do this by recursively looking for the Parent control by name and type using the 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;
    }


来源:https://stackoverflow.com/questions/15198104/find-parent-of-control-by-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!