Find control parent by name

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

+5
source share
3 answers

Try it,

element = VisualTreeHelper.GetParent(element) as UIElement;   

Where, the element of which is Children - Whose parent you should receive.

+8
source

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

XAML, " ", , , , , .

, "" , "ParentSearcher" , " ", XAML.

?

+1

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;
    }
0

All Articles