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

Leave a Reply

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