All of these answers are very nice, but, if you're trying to find a specific visual child of type T, you're either stuck getting them all and then finding the one you want, or hoping the first one you get is the one you want. I merged a few approaches to find a specific one based on a criteria. It's a bit like LINQ, but I didn't want to try to deal with a recursive enumerator.
Use it like this:
MyContainer.FirstOrDefaultChild<Label>(l => l.Content=="State")
I wrote it as an extension method.
public static class DependencyObjectExtensions
{
public static T FirstOrDefaultChild<T>(this DependencyObject parent, Func<T, bool> selector)
where T : DependencyObject
{
T foundChild;
return FirstOrDefaultVisualChildWhere(parent, selector, out foundChild) ? foundChild : default(T);
}
private static bool FirstOrDefaultVisualChildWhere<T>(DependencyObject parent, Func<T, bool> selector,
out T foundChild) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parent);
for (var i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
var tChild = child as T;
if (tChild != null)
{
if (!selector(tChild)) continue;
foundChild = tChild;
return true;
}
if (FirstOrDefaultVisualChildWhere(child, selector, out foundChild))
{
return true;
}
}
foundChild = default(T);
return false;
}
LogicalTreeHelper.FindLogicalNode(DependencyObject depObj, string elementName)
worked for me to achieve the same goal. – Considering