WPF - How to find an object contained within another object? [duplicate]
I have a TabControl in a window and several tab items in the control. How would I go about finding say all TextBox controls that are contained within one of the tab items?
Than开发者_JAVA技巧ks.
Something like this:
public static IEnumerable<T> FindDescendants<T>(DependencyObject obj, Predicate<T> condition) where T : DependencyObject
{
List<T> result = new List<T>();
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
var child = VisualTreeHelper.GetChild(obj, i);
var candidate = child as T;
if (candidate != null)
{
if (condition(candidate))
{
result.Add(candidate);
}
}
foreach (var desc in FindDescendants(child, condition))
{
result.Add(desc);
}
}
return result;
}
And in case of finding all text boxes in a tab item the method call will look like this:
var allTextBoxes = FindDescendants<TextBox>(myTabItem, e => true);
精彩评论