递归类型特定的控制enable.state设置

时间:2015-08-07 16:35:11

标签: vb.net controls

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

我目前(下面)的代码由于某种原因似乎忽略了GroupBox控件(我意识到我只用了一个Form容器尝试了它,但它确实有效。)

Private Sub ChangeControlEnabledState(Of T As Control)(cc As ContainerControl, state As Boolean)
    Dim cl As ControlCollection = cc.Controls
    For Each c As Object In cc.Controls ' 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 TypeOf c Is ContainerControl Then    ' Check if the object is a "sub" container type
            ChangeControlEnabledState(Of T)(c, state)   ' Recurse to handle the controls within the "sub" container
        End If
    Next
End Sub

'Usage
ChangeControlEnabledState(Of Button)(Me, False) 'Changes all buttons on this form to Button.Enabled = false

可能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

但是当尝试递归时,这会在第一个GroupBox上引发异常:

  

System.InvalidCastException {" [A] ControlCollection无法转换为[B] ControlCollection。类型A源自' System.Windows.Forms,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089'在上下文中'默认'在位置' C:\ Windows \ Microsoft.Net \ assembly \ GAC_MSIL \ System.Windows.Forms \ v4.0_4.0.0.0__b77a5c561934e089 \ System.Windows.Forms.dll'。类型B源自' System.Windows.Forms,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089'在上下文中'默认'在位置' C:\ Windows \ Microsoft.Net \ assembly \ GAC_MSIL \ System.Windows.Forms \ v4.0_4.0.0.0__b77a5c561934e089 \ System.Windows.Forms.dll'。"}系统.InvalidCastException

对于我有限的理解,似乎说X类型的强制转换不能用于输入X,因为它是X型...

2 个答案:

答案 0 :(得分:2)

不确定这会有所帮助,但我使用control.haschildren来确定递归调用。

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

我从初始化子句中调用此子句:

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

我是表格。

答案 1 :(得分:0)

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

只需使用Control.ContainerControl进行显式定义,此错误就会消失!