Find all controls in WPF Window by type

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

    I adapted @Bryce Kahle's answer to follow @Mathias Lykkegaard Lorenzen's suggestion and use LogicalTreeHelper.

    Seems to work okay. ;)

    public static IEnumerable FindLogicalChildren ( DependencyObject depObj ) where T : DependencyObject
    {
        if( depObj != null )
        {
            foreach( object rawChild in LogicalTreeHelper.GetChildren( depObj ) )
            {
                if( rawChild is DependencyObject )
                {
                    DependencyObject child = (DependencyObject)rawChild;
                    if( child is T )
                    {
                        yield return (T)child;
                    }
    
                    foreach( T childOfChild in FindLogicalChildren( child ) ) 
                    {
                        yield return childOfChild;
                    }
                }
            }
        }
    }
    

    (It still won't check tab controls or Grids inside GroupBoxes as mentioned by @Benjamin Berry & @David R respectively.) (Also followed @noonand's suggestion & removed the redundant child != null)

提交回复
热议问题