开发者

WPF - How to find an object contained within another object? [duplicate]

This question already has answers here: Find all controls in WPF Window by type (17 answers) Closed 7 months ago.

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜