user2025830
user2025830

Reputation: 902

Find Parent of Control by Name

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

Upvotes: 14

Views: 24655

Answers (3)

Marc
Marc

Reputation: 13184

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.

Upvotes: 2

ScottyMacDev
ScottyMacDev

Reputation: 182

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

Upvotes: 10

Arun Selva Kumar
Arun Selva Kumar

Reputation: 2732

Try this,

element = VisualTreeHelper.GetParent(element) as UIElement;   

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

Upvotes: 9

Related Questions