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;
}
Anonymous User
15-Mar-2019Very nice blog.
Anonymous User
19-May-2011