Users Pricing

blog

home / developersection / blogs / how to find parent of control in wpf

How to Find Parent of Control in WPF

Anonymous User 33677 05 May 2011 Updated 18 Sep 2014

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.


I am a content writter !


2 Comments