Wine Too
Wine Too

Reputation: 4655

Set Font.Bold on inherited label

I have to set .Font.Bold = True on label which havent defined .Font property but inherite Font (name, size, style) from form. For that I erases her .Font property from form's designer file.

Now I need to set text of this label to be bold without defining font name, size etc. for this label.

I try:

label6.Font.Bold = True

But this don't work (Property .Font.Bold is readonly).
If I set font for this label like:

label6.Font = New Font(myfontname, 10, FontStyle.Bold, GraphicsUnit.Point)

then I get bold text but label then don't inherite form's font size anymore.

Is here possible to keep form's font inheritance to label but get bold text on such label?

Upvotes: 2

Views: 8773

Answers (1)

Cody Gray
Cody Gray

Reputation: 244782

No, as you've already discovered the Font.Bold property is read-only. Font objects are immutable, meaning that their properties cannot be changed once they have been created. The only way to modify this property is to create a new Font object.

When creating this new Font, you can certainly copy the properties of an existing Font object (like the one used by your form), but there is no way to dynamically couple the two Font objects together. If the font size used by your form changes, a new Font object will be created with that new size for the form, but your custom bold Font object will not be updated.

The only thing that makes this confusing is that there is a bit of magic that goes on if you do not set a custom font for child controls. They automatically inherit the font of their parent (a container control, such as a form). Such properties that retrieve their value from their parent when they have not been explicitly set are referred to as ambient properties. Ambient properties are explained in the documentation where applicable. But the upshot is that the ambience goes away at the point where you explicitly set the property. So forget about that.

To achieve what you want, we need to get a notification when the form's font size changes and in response, you can create a new bold Font object with the new size for your Label control. Luckily, there is just such a mechanism in the form of the FontChanged event. Handle the FontChanged event for your form, and in response, create a new Font object for your Label control. For example:

Private Sub myForm_FontChanged(ByVal sender As Object, ByVal e As EventArgs) Handles myForm.FontChanged
    Dim oldFont As Font = myLabel.Font
    myLabel.Font = New Font(myForm.Font, myForm.Font.Style Or FontStyle.Bold)
    oldFont.Dispose()
End Sub

Although, I'm not sure if/why this is really necessary. It's rare that the font size of a form gets changed while the application is running. Generally that happens only at creation, in which case when you retrieve the value to create the custom Font object for your Label control, it would already be set correctly.

Upvotes: 5

Related Questions