How can I change the ForeColor of the GroupBox text without changing its children ForeColor?

坚强是说给别人听的谎言 提交于 2020-01-04 09:24:07

问题


I want to know if there is an option to just change the color of group box text at the top left of the group box in a windows form and not any controls or labels located inside of the group box.

I know that GroupBox.ForeColor = Color.Blue will change all text associated with that box to blue, but it also changes the ForeColor of labels and other controls in the GroupBox.

How can I change the color of the group box text without changing its children forecolor?


回答1:


The ForeColor property is an ambient property. An ambient property is a control property that, if not set, is retrieved from the parent control.

Since you didn't set ForeColor for the labels and textboxes in the group box, they will use ForeColor value of their parent. You can solve this problem using either of these options:

  1. Put a Panel in GroupBox Set the ForeColor of GroupBox to Blue and set ForeColor of Panel to ControlText explicitly using designer. Then put other controls in the Panel. This way, your controls will use ForeColor of Panel which you set explicitly.

  2. Customize Paint of GroupBox:

    Private Sub GroupBox1_Paint(ByVal sender As System.Object, _
        ByVal e As System.Windows.Forms.PaintEventArgs) Handles GroupBox1.Paint
    
        e.Graphics.Clear(Me.GroupBox1.BackColor)
        GroupBoxRenderer.DrawGroupBox(e.Graphics, Me.GroupBox1.ClientRectangle, _
            Me.GroupBox1.Text, Me.GroupBox1.Font, Color.Blue, _
            System.Windows.Forms.VisualStyles.GroupBoxState.Normal)
    End Sub
    



回答2:


As long as I know, all the child controls will take the property of the parent.

You can store all your child colors and change them after you set the GroupBox's ForeColor. You can use a Dictionary with each pair of Control/Color.

Something like:

Dim cColors As New Dictionary(Of Control, Color)

For Each ctrl As Control In GroupBox1.Controls
    cColors.Add(ctrl, ctrl.ForeColor)
Next

GroupBox1.ForeColor = Color.Blue

For Each ctrl As Control In GroupBox1.Controls
    If cColors.HasKey(ctrl) Then
        ctrl.ForeColor = cColors(ctrl)
    End If
Next

You can put that in a method.

More information about the property at MSDN.



来源:https://stackoverflow.com/questions/37793517/how-can-i-change-the-forecolor-of-the-groupbox-text-without-changing-its-childre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!