问题
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:
Put a
Panel
inGroupBox
Set theForeColor
ofGroupBox
toBlue
and setForeColor
ofPanel
toControlText
explicitly using designer. Then put other controls in thePanel
. This way, your controls will useForeColor
ofPanel
which you set explicitly.Customize
Paint
ofGroupBox
: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