blog

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

How to Find Parent of Control in WPF

Anonymous User32670 05-May-2011

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.


Updated 18-Sep-2014
I am a content writter !

Leave Comment

Comments

Liked By