粗体、斜体和下划线 -vb.net
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41790333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bold, Italic and Underline -vb.net
提问by TGamer
My program makes labels bold, italic, or underline depending on the button clicked. But when I attempt to have both effects at once the first fades off.
我的程序根据单击的按钮将标签设为粗体、斜体或下划线。但是当我试图同时拥有这两种效果时,第一种效果就会消失。
Private Sub bold_Click(sender As Object, e As EventArgs) Handles bold.Click
Dim con4 As Control
For Each con4 In Me.Controls
Select Case con4.Name
Case "Label1"
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
Case "Label2"
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
...
...
End Select
Next
End Sub
This code goes up to Label24.
此代码上升到 Label24。
So I use the same procedure for 3 different buttons and they get me my result. But attempting to have 2 effects together overrides the previous one.
所以我对 3 个不同的按钮使用相同的程序,他们得到了我的结果。但是尝试将 2 个效果放在一起会覆盖前一个效果。
Thanks guys.
谢谢你们。
回答by usr2564301
You override the font style with the very next test because you inspect-and-set all conditions only one at a time.
您可以在下一个测试中覆盖字体样式,因为您一次只检查并设置所有条件。
Combine the tests for each label once, then pick the right font:
将每个标签的测试组合一次,然后选择正确的字体:
If con4.Font.Bold = False Then
If con4.Font.Italic = False Then
con4.Font = New Font(con4.Font, FontStyle.Bold Or FontSryle.Italic)
Else ' not italic
con4.Font = New Font(con4.Font, FontStyle.Bold)
End If
Else ' not bold
If con4.Font.Italic = False Then
con4.Font = New Font(con4.Font, FontStyle.Italic)
Else ' not italic
con4.Font = New Font(con4.Font, FontStyle.Regular)
End If
End If
As you can see, this gets unwieldy very fast; especially if you are repeating the same code for 24 labels. So, step #1 would be to make this sequence a function.
如您所见,这很快变得笨拙;特别是如果您对 24 个标签重复相同的代码。因此,第 1 步是使这个序列成为一个函数。
Step #2 is to get rid of all those comparisons - adding Underline would add yet another level of if..else..end iffor all of the separate cases! You can combine FontStylebits with an Orto form the final value, and only then set it:
步骤 #2 是摆脱所有这些比较 - 添加下划线将为if..else..end if所有单独的案例添加另一个级别!您可以将FontStyle位与 an组合Or以形成最终值,然后才设置它:
fontstyle = FontStyle.Regular
If cond4.Font.Bold = False Then
fontstyle = fontStyle.Bold
End If
If cond4.Font.Italic = False Then
fontstyle = fontstyle Or fontStyle.Italic
End If
If cond4.Font.Underline = False Then
fontstyle = fontstyle Or fontStyle.Underline
End If
target.Font = New Font(con4.Font, fontstyle)
(This may not entirely be the correct syntax, but the general idea should be clear.)
(这可能不完全是正确的语法,但总体思路应该很清楚。)

