1

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?

Thanks.

Hosea146
  • 7,412
  • 21
  • 60
  • 81

1 Answers1

1

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);
Pavlo Glazkov
  • 20,498
  • 3
  • 58
  • 71