Find all controls in WPF Window by type

后端 未结 17 1233
春和景丽
春和景丽 2020-11-21 10:14

I\'m looking for a way to find all controls on Window by their type,

for example: find all TextBoxes, find all controls implementing specific i

17条回答
  •  渐次进展
    2020-11-21 10:41

    For this and more use cases you can add flowing extension method to your library:

     public static List FindAllChildren(this DependencyObject dpo, Predicate predicate)
        {
            var results = new List();
            if (predicate == null)
                return results;
    
    
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dpo); i++)
            {
                var child = VisualTreeHelper.GetChild(dpo, i);
                if (predicate(child))
                    results.Add(child);
    
                var subChildren = child.FindAllChildren(predicate);
                results.AddRange(subChildren);
            }
            return results;
        }
    

    Example for your case:

     var children = dpObject.FindAllChildren(child => child is TextBox);
    

提交回复
热议问题