Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 881
user2025830 Avatar asked Jan 26 '26 12:01

user2025830


2 Answers

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;
    }
like image 150
ScottyMacDev Avatar answered Jan 28 '26 09:01

ScottyMacDev


Try this,

element = VisualTreeHelper.GetParent(element) as UIElement;   

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

like image 32
Arun Selva Kumar Avatar answered Jan 28 '26 08:01

Arun Selva Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!