首页 文章

将多种字体样式应用于标签 - vb.net

提问于
浏览
0

我有一个程序,它将粗体,斜体和下划线(每个都有一个按钮点击)应用于标签 . 但我不能有2 fontstyles ,就像一个同时用粗体和斜体的单词 . 我尝试过的以下代码将使用新代码覆盖以前应用的样式 .

Dim con4 As Label
For Each con4 In Me.Controls
   If con4.Font.Bold = False Then
        con4.Font = New Font(con4.Font, FontStyle.Bold)
   Else
        con4.Font = New Font(con4.Font, FontStyle.Regular)
   End If

我想要做的是,当单击按钮并且标签正常时将标签更改为粗体,如果标签已经是粗体,则将其恢复为正常 .

我使用相同的代码斜体和下划线,但我使用 con5con6

我很快就看到,这不允许我制作Label Bold和Italic . 每个按钮单击会覆盖前一个按钮 . 所以,如果你能告诉我到底该怎么做 .


多谢你们 .

1 回答

  • 3

    FontStyle 枚举应用了 Flags 属性,这意味着您可以将值与 Or 运算符组合在一起 . 例如,要同时应用Bold和Italic,您可以使用:

    FontStyle.Bold Or FontStyle.Italic
    

    您拥有的代码实际上是切换单个样式,最正确的方法是这样:

    myFont = New Font(myFont, myFont.Style Xor FontStyle.Bold)
    

    这将适用 Bold 如果不是,如果它不影响任何其他样式,则删除它,因此您可以有两个单独的按钮或菜单项,每个按钮或菜单项切换一种样式 .

    如果您希望能够选择应用多种样式,例如使用 CheckBoxes 然后我会建议这样的事情:

    Dim style = FontStyle.Regular
    
    If useBold Then
        style = style Or FontStyle.Bold
    End If
    
    If useItalic Then
        style = style Or FontStyle.Italic
    End If
    
    myFont = New Font(myFont, style)
    

    编辑:

    这是一个更完整的例子,我只是使用 Buttons 来切换样式:

    Private Sub boldButton_Click(sender As Object, e As EventArgs) Handles boldButton.Click
        ToggleStyle(FontStyle.Bold)
    End Sub
    
    Private Sub italicButton_Click(sender As Object, e As EventArgs) Handles italicButton.Click
        ToggleStyle(FontStyle.Italic)
    End Sub
    
    Private Sub underlineButton_Click(sender As Object, e As EventArgs) Handles underlineButton.Click
        ToggleStyle(FontStyle.Underline)
    End Sub
    
    Private Sub ToggleStyle(style As FontStyle)
        Me.Label1.Font = New Font(Me.Label1.Font, Me.Label1.Font.Style Xor style)
    End Sub
    

    这是一个类似的例子,使用 CheckBoxes 来选择样式:

    Private Sub boldCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles boldCheckBox.CheckedChanged
        SetStyle()
    End Sub
    
    Private Sub italicCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles italicCheckBox.CheckedChanged
        SetStyle()
    End Sub
    
    Private Sub underlineCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles underlineCheckBox.CheckedChanged
        SetStyle()
    End Sub
    
    Private Sub SetStyle()
        Dim style = FontStyle.Regular
    
        If Me.boldCheckBox.Checked Then
            style = style Or FontStyle.Bold
        End If
    
        If Me.italicCheckBox.Checked Then
            style = style Or FontStyle.Italic
        End If
    
        If Me.underlineCheckBox.Checked Then
            style = style Or FontStyle.Underline
        End If
    
        Me.Label1.Font = New Font(Me.Label1.Font, style)
    End Sub
    

相关问题