Home > DeveloperSection > Blogs > How to Find Parent of Control in WPF

How to Find Parent of Control in WPF


WPF WPF 
Ratings:
1 Comment(s)
 18514  View(s)
Rate this:


How to Find Parent of Control in WPF


There are many situations where we need to refer to the parent container/control of specific type of control/item in WPF. Suppose we want to get ListViewItem on which a Button control is placed or we want to get the reference of that ListView in WPF.

Here is a method through which we can find parent of a control.

/// <summary>

/// Finds a parent of a given control/item on the visual tree.

/// </summary>

/// <typeparam name="T">Type of Parent</typeparam>

/// <param name="child">Child whose parent is queried</param>

/// <returns>Returns the first parent item that matched the type (T), if no match found then it will return null</returns>

public static T TryFindParent<T>(this DependencyObject child)

where T : DependencyObject

{

DependencyObject parentObject = VisualTreeHelper.GetParent(child);

if (parentObject == null) return null;

       T parent = parentObject as T;

       if (parent != null)

              return parent;

else

              return TryFindParent<T>(parentObject);

}

 

Hope you will find this blog heplful.


Function in use

By Antonio Bou on   one year ago
HI,

Tested this function and seem to work correctly. Thanks pal, you helped me a lot.

Regards.

Don't want to miss updates? Please click the below button!

Follow MindStick