Home > DeveloperSection > Blogs > How to Find Child of Control in WPF

How to Find Child of Control in WPF


WPF WPF 
Ratings:
1 Comment(s)
 18419  View(s)
Rate this:


How to Find Child of Control in WPF


Sonetime 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 fing 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;

}

 

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


How to find control in WPF.

By Awadhendra Tiwari on   5 years ago
Its very good article.

Don't want to miss updates? Please click the below button!

Follow MindStick