Here’s a simple function you can use to get a specific child from a given visual tree. For example, you may want to get a handle to the scrollviewer in a listbox control. Here’s how you’d use the function to do that :-
ScrollViewer scrollViewer = FindChildControl<ScrollViewer>(searchResultsListbox);
And here’s the function listing :-
private T FindChildControl<T>(DependencyObject outerDepObj) where T:DependencyObject
{
T child = null;
for (int index = 0; index < VisualTreeHelper.GetChildrenCount(outerDepObj); index++)
{
DependencyObject depObj = VisualTreeHelper.GetChild(outerDepObj, index);
if (depObj is T)
{
child = depObj as T;
}
else if (VisualTreeHelper.GetChildrenCount(depObj) > 0)
{
child = FindChildControl<T>(depObj);
}
if (child != null)
{
break;
}
}
return child;
}