Getting parent control of a control in WPF through code or at runtime

I was working on a WPF project where I came across a problem where I need to refer to the parent container/control of specific type of control/item in WPF. So I did some RnD and search on the net for the problem and finally I came across a solution which I want to share.

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);

To find child control of a control, refer to Find Child Control of a Control in WPF.

Hope you will find this blog helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *