Find all controls in WPF Window by type

后端 未结 17 1267
春和景丽
春和景丽 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:46

    Here is yet another, compact version, with the generics syntax:

        public static IEnumerable FindLogicalChildren(DependencyObject obj) where T : DependencyObject
        {
            if (obj != null) {
                if (obj is T)
                    yield return obj as T;
    
                foreach (DependencyObject child in LogicalTreeHelper.GetChildren(obj).OfType()) 
                    foreach (T c in FindLogicalChildren(child)) 
                        yield return c;
            }
        }
    

提交回复
热议问题