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;
}
There is a double cast to T in the code. IMO code it can be reduced to, that only one cast (operator “as”) will be performed.
if ((child = depObj as T) != null)
{
break;
}
else if (VisualTreeHelper.GetChildrenCount(depObj) > 0)
{
child = FindChildControl(depObj);
}
I figured out our code to make it find a parent object.
public static T FindParentControl(DependencyObject innerDepObj) where T : DependencyObject
{
T parent = null;
while (innerDepObj != null)
{
innerDepObj = VisualTreeHelper.GetParent(innerDepObj);
if (innerDepObj is T)
{
parent = innerDepObj as T;
break;
}
}
return parent;
}