【问题标题】:VB - Change Colors on Children doesn't workVB - 更改儿童的颜色不起作用
【发布时间】:2017-07-20 08:53:50
【问题描述】:

我创建了一个 For Each 循环,该循环遍历所有控件并在找到时更改其颜色。问题是,它不会改变标签的颜色:

Sub SetColorSettings(ByVal parent As Control)

    parent.SuspendLayout()

    For Each c As Control In parent.Controls
        If TypeOf (c) Is TableLayoutPanel Then
            c.BackColor = Color.White
        ElseIf TypeOf (c) Is Label Then
            c.ForeColor = Color.Black
        Else
            If c.HasChildren Then
                SetColorSettings(c)
            End If
        End If
    Next

    parent.ResumeLayout()
    parent.Refresh()

End Sub

然后我在另一个子或函数中应用 SetColorSettings(Me) 的更改。

注意:在我的表单中,标签直接放置在表格布局面板中,所以从技术上讲,标签应该是表格布局面板的子级。

我个人认为这些台词在某种程度上让我感到困惑:

If c.HasChildren Then
    SetColorSettings(c)
End If

【问题讨论】:

  • 您是否尝试调试您的代码以查看流程?我猜如果控件是 TableLayoutPanel 你没有为它的孩子调用方法
  • @Pikoh,感谢您的快速回答,我对 Visual Studio 很陌生,所以调试工具对我来说是新事物。你能告诉我应该从哪里开始寻找这方面的信息吗?
  • 好吧,那么您的第一步就是学习在 Visual Studio 中进行调试。基本功,见this documentation
  • 感谢有关调试的文档,它的工作方式与其他软件类似。我发现 For Each 循环遍历表格布局面板之外的所有标签并更改它们。在表格布局面板中,它从不“选择/查找”标签。所以看起来你在正确的轨道上。我需要找到一种方法来访问表格布局面板中的标签。我还注意到它从未登陆SetColorSettings(c) 编辑:原始代码:stackoverflow.com/questions/43317174/…
  • 试试我回答中的代码,告诉我是否有帮助

标签: vb.net


【解决方案1】:

问题在于,如果控件是TableLayoutPanel,则您不会为其子级调用该方法。每次控件有孩子时,您都必须致电SetColorSettings(c)。试试这个代码:

Sub SetColorSettings(ByVal parent As Control)

parent.SuspendLayout()

For Each c As Control In parent.Controls
    If TypeOf (c) Is TableLayoutPanel Then
        c.BackColor = Color.White
    ElseIf TypeOf (c) Is Label Then
        c.ForeColor = Color.Black
    End If

    If c.HasChildren Then
        SetColorSettings(c)
    End If

Next

parent.ResumeLayout()
parent.Refresh()

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 2012-02-13
    相关资源
    最近更新 更多