Find all controls in WPF Window by type

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

    @Bryce, really nice answer.

    VB.NET version:

    Public Shared Iterator Function FindVisualChildren(Of T As DependencyObject)(depObj As DependencyObject) As IEnumerable(Of T)
        If depObj IsNot Nothing Then
            For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(depObj) - 1
                Dim child As DependencyObject = VisualTreeHelper.GetChild(depObj, i)
                If child IsNot Nothing AndAlso TypeOf child Is T Then
                    Yield DirectCast(child, T)
                End If
                For Each childOfChild As T In FindVisualChildren(Of T)(child)
                    Yield childOfChild
                Next
            Next
        End If
    End Function
    

    Usage (this disables all TextBoxes in a window):

            For Each tb As TextBox In FindVisualChildren(Of TextBox)(Me)
              tb.IsEnabled = False
            Next
    

提交回复
热议问题