我在调整RichTextBox中的字体样式时遇到了麻烦,我看到了几种不同的方法来讨论单个属性(比如打开和关闭粗体)......但我试图让它变得如此我的字体类可以调整任何属性(粗体,斜体,下划线)。
我意识到Font.Style是一组布尔标志(一个位域?)......但我不知道如何一次处理所有属性。
这是一个麻烦的代码:
Public Sub ModifyFontStyle(Optional ByVal Plain As Object = Nothing, Optional ByVal Bold As Object = Nothing, _
Optional ByVal Italics As Object = Nothing, Optional ByVal Underlined As Object = Nothing)
Dim newFontStyle As System.Drawing.FontStyle
If Plain Then
newFontStyle = Drawing.FontStyle.Regular
GivenFont = New Drawing.Font(GivenFont.FontFamily, GivenFont.Size, newFontStyle)
Exit Sub
End If
If Bold IsNot Nothing Then
If Bold Then
newFontStyle = GivenFont.Style + Drawing.FontStyle.Bold
Else
newFontStyle = GivenFont.Style - Drawing.FontStyle.Bold
End If
End If
If Italics IsNot Nothing Then
If Italics Then
newFontStyle = GivenFont.Style + Drawing.FontStyle.Italic
Else
newFontStyle = GivenFont.Style - Drawing.FontStyle.Italic
End If
End If
If Underlined IsNot Nothing Then
If Underlined Then
newFontStyle = GivenFont.Style + Drawing.FontStyle.Underline
Else
newFontStyle = GivenFont.Style - Drawing.FontStyle.Underline
End If
End If
GivenFont = New Drawing.Font(GivenFont.FontFamily, GivenFont.Size, newFontStyle)
End Sub
以下是此代码的最终问题:
字体发生了什么?该文本应加下划线,斜体字不得删除......
这是我的逻辑错误还是简单的误解?
好的,谢谢你的时间,我会继续修补它,直到它工作或我得到一个有效的答案,
答案 0 :(得分:3)
您使用的是错误的运算符。它们确实类似于位标志,枚举具有[Flags]属性。您需要使用Or运算符打开样式,使用And运算符关闭样式。像这样:
Dim style = Me.Font.Style
'--- turn bold on
style = style Or FontStyle.Bold
'--- turn bold off
style = style And Not FontStyle.Bold
答案 1 :(得分:0)
Public Sub ModifyFontStyle(Optional ByVal Plain As Object = Nothing, Optional ByVal Bold As Object = Nothing, _
Optional ByVal Italics As Object = Nothing, Optional ByVal Underlined As Object = Nothing)
Dim newFontStyle As System.Drawing.FontStyle
If Plain Then
newFontStyle = Drawing.FontStyle.Regular
GivenFont = New Drawing.Font(GivenFont.FontFamily, GivenFont.Size, newFontStyle)
Exit Sub
End If
If Bold IsNot Nothing Then
If Bold And Not GivenFont.Bold Then
newFontStyle = GivenFont.Style + Drawing.FontStyle.Bold
Else
newFontStyle = GivenFont.Style - Drawing.FontStyle.Bold
End If
End If
If Italics IsNot Nothing Then
If Italics And Not GivenFont.Italic Then
newFontStyle = GivenFont.Style + Drawing.FontStyle.Italic
Else
newFontStyle = GivenFont.Style - Drawing.FontStyle.Italic
End If
End If
If Underlined IsNot Nothing Then
If Underlined And Not GivenFont.Underline Then
newFontStyle = GivenFont.Style + Drawing.FontStyle.Underline
Else
newFontStyle = GivenFont.Style - Drawing.FontStyle.Underline
End If
End If
GivenFont = New Drawing.Font(GivenFont.FontFamily, GivenFont.Size, newFontStyle)
End Sub
谢谢你的时间!