Vb.net 递归类型特定控件的enable.state设置

Vb.net 递归类型特定控件的enable.state设置,vb.net,controls,Vb.net,Controls,我正在尝试构建一个快速子控件,它将禁用表单上以及该表单上任何容器中给定类型的所有控件,例如GroupBox 由于某种原因,我现在(下面)看到的代码似乎忽略了GroupBox控件(我意识到我只在表单容器中尝试过它,但它确实有效) 也许GroupBox不是ContainerControl 编辑: 对此进行了调整: For Each c As Control In cc ' Iterate through every object in the container

我正在尝试构建一个快速子控件,它将禁用表单上以及该表单上任何容器中给定类型的所有控件,例如
GroupBox

由于某种原因,我现在(下面)看到的代码似乎忽略了GroupBox控件(我意识到我只在
表单
容器中尝试过它,但它确实有效)

也许
GroupBox
不是
ContainerControl

编辑: 对此进行了调整:

        For Each c As Control In cc ' Iterate through every object in the container
            If TypeOf c Is T Then   ' Check if the object matches the type to set the state on
                CType(c, T).Enabled = state ' Set the state on the matching object
            ElseIf c.HasChildren Then  ' Check if the control has children
                ChangeControlEnabledState(Of T)(c.Controls, state)   ' Recurse to handle the child controls
            End If
        Next
但在尝试递归时,这会在第一个
组框上引发异常:

System.InvalidCastException{“[A]ControlCollection无法强制转换为[B]ControlCollection.Type A源自位置“C:\Windows\Microsoft.Net\assembly\GAC\U MSIL\System.Windows.Forms\v4.0\U 4.0.0\UUU b77a5c561934e089\System.Windows.Forms.dll”的上下文“Default”中的“System.Windows.Forms,Version=4.0.0.0\UUUU B77A561934E089\System.Windows.Forms.dll”。类型B源自“System.Windows.Forms,Version=4.0”.0.0,区域性=中性,PublicKeyToken=b77a5c561934e089'在位置“C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0_b77a5c561934e089\System.Windows.Forms.dll.”的上下文“默认值”中。}System.InvalidCastException


就我有限的理解而言,这似乎表明不能将类型X转换为类型X,因为它是类型X。

不确定这是否有帮助,但我使用control.haschilds来确定递归调用

Private Sub SetEnterHandler(ByVal ParentCtrl As Control)
    'recursive call to find all controls that can have focus
    For Each c As Control In ParentCtrl.Controls
        If c.HasChildren Then
            SetEnterHandler(c)
        Else
            'do non-container stuff here
        End If
    Next
End Sub
我从正在初始化的sub调用此sub:

    For Each c As Control In Me.Controls
        If c.HasChildren Then SetEnterHandler(c)
    Next

其中Me是表单。

此错误是因为
ContainerControl
是在“
System.Windows.Forms
”命名空间中的
Control
类中定义的,它是表单和任何控件的父类。
Control
中的所有子类都在生成它们自己的ControlCollection类,而这并不是真正需要的


只要使用
Control.ContainerControl
来显式定义,这个错误就会消失

我已尝试更改为
ElseIf(c.GetType).GetField(“控件”)然后不是什么都没有…
但是没有骰子。打开选项Strict,不要阻塞循环iterator@Plutonix如果我让我父亲感到不安的话,我想这就是我父亲常说的:p但除此之外,我恐怕不知道那是什么意思
Control.ControlCollection
而不是
ControlCollection
,因为子参数类型特例的技巧。愚蠢的泛型对象不是泛型的,除非它们是泛型的。但有时他们仍然不是。。。好的,这有助于确定是否存在完美的子控件,现在我只需要能够将父控件转换为接受任何父控件的泛型控件(而不仅仅是
容器控件,它不是任何包含控件的控件)。我是否必须像
控件那样通用,或者是否有比它更紧密的类型来涵盖所有可以有子控件的控件?不,我认为控件差不多是你能做到的最紧密的了。Private Sub ChangeControlEnabledState(属于T as Control)(cc as Control,state as Boolean)对于cc中的每个c As控件。如果c的类型为T,则控制CType(c,T)。Enabled=状态ElseIf c.HasChildren,然后更改ControlEnabledState(Of T)(c,状态)End If Next End Sub
    For Each c As Control In Me.Controls
        If c.HasChildren Then SetEnterHandler(c)
    Next