Author : Admin
Last Modified : 23-Mar-2022
Complexity : Beginner

How to get parent control in wpf?

WPF provides the VisualTreeHelper.GetParent(DependencyObject) method to find the parent of a control. Every UI element in WPF is a DependencyObject so the child UI element can be passed to the GetParent() method. Below is the implementation to find the parent element.

     public static class GTVisualTreeHelper
       //Finds the visual parent.
       public static T FindVisualParent<T>(DependencyObject child) where T : DependencyObject
           if (child == null)
               return (null);
           //get parent item
           DependencyObject parentObj = VisualTreeHelper.GetParent(child);
           //we've reached the end of the tree
           if (parentObj == null) return null;
           // check if the parent matches the type we are requested
           T parent = parentObj as T;
           if (parent != null)
               return parent;
               // here, To find the next parent in the tree. we are using recursion until we found the requested type or reached to the end of tree.
               return FindVisualParent<T>(parentObj);

Suppose we have a button inside the user control and we have access to the button in code and want to find the user control. The below code snippet shows you to find the UserControl.

How to use    

UserControl parent = GTVisualTreeHelper.FindVisualParent<UserControl>(btnSave);

In a similar fashion, We can find parent control of the desired type of any child control.