Find child control of a control in WPF

Sometime we want to get reference of child control of container control of specified type. Example we want to find CheckBox control inside ListViewItem or we want to find another container Panel inside a Grid.

Here is a method through which we can find child control inside a parent control. The method below will return the first matching control of the specified type (T), if control of specified type is not found in the provided parent control it will return null.

/// <summary>
/// Method to get child control of specified type
/// </summary>
/// <typeparam name="T">Type of child control queried</typeparam>
/// <param name="parent">Reference of parent control in which child control resides</param>
/// <returns>Returns reference of child control of specified type (T) if found, otherwise it will return null.</returns>

private static T FindVisualChild<T>(DependencyObject parent)
where T : DependencyObject
{
     for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
     {
          DependencyObject child = VisualTreeHelper.GetChild(parent, i);

          if (child != null && child is T)
               return (T)child;
          else
          {
               T childOfChild = FindVisualChild<T>(child);
               if (childOfChild != null)
                    return childOfChild;
          }
     }
return null;
}

To find parent control of a control in WPF, refer to Getting Parent Control of a Contol in WPF through Code or at Run-time.

Hope you will find it helpful, if you have any doubt please feel free to ask.

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;
     else
          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.