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;
              return TryFindParent<T>(parentObject);


Hope you will find this blog heplful.

  Modified On Sep-18-2014 01:23:55 PM
  1. HI,

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


Leave Comment