How can I find WPF controls by name or type?

后端 未结 18 2926
庸人自扰
庸人自扰 2020-11-21 04:23

I need to search a WPF control hierarchy for controls that match a given name or type. How can I do this?

18条回答
  •  囚心锁ツ
    2020-11-21 05:08

    Here is a solution that uses a flexible predicate:

    public static DependencyObject FindChild(DependencyObject parent, Func predicate)
    {
        if (parent == null) return null;
    
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
    
            if (predicate(child))
            {
                return child;
            }
            else
            {
                var foundChild = FindChild(child, predicate);
                if (foundChild != null)
                    return foundChild;
            }
        }
    
        return null;
    }
    

    You can for example call it like this:

    var child = FindChild(parent, child =>
    {
        var textBlock = child as TextBlock;
        if (textBlock != null && textBlock.Name == "MyTextBlock")
            return true;
        else
            return false;
    }) as TextBlock;
    

提交回复
热议问题