Friday, January 3, 2020

Changing Font Properties in VB.NET

Bold is read-only in VB.NET. This article tells you how to change that. In VB6, it was dead easy to change a font to bold. You simply coded something like Label1.FontBold, but in VB.NET, the Bold property of the Font object for a Label is read-only. So how do you change it? Changing Font Properties in VB.NET With Windows Forms Heres the basic code pattern for Windows Forms. Private Sub BoldCheckbox_CheckedChanged( _ByVal sender As System.Object, _ByVal e As System.EventArgs) _Handles BoldCheckbox.CheckedChangedIf BoldCheckbox.CheckState CheckState.Checked ThenTextToBeBold.Font _New Font(TextToBeBold.Font, FontStyle.Bold)ElseTextToBeBold.Font _New Font(TextToBeBold.Font, FontStyle.Regular)End IfEnd Sub Theres a lot more than Label1.FontBold, thats for sure. In .NET, fonts are immutable. That means once they are created they cannot be updated. VB.NET gives you more control than you get with VB6 over what your program is doing, but the cost is that you have to write the code to get that control. VB6 will internally drop one GDI font resource and create a new one. With VB.NET, you have to do it yourself. You can make things a little more global by adding a global declaration at the top of your form: Private fBold As New Font(Arial, FontStyle.Bold)Private fNormal As New Font(Arial, FontStyle.Regular) Then you can code: TextToBeBold.Font fBold Note that the global declaration now specifies the font family, Arial, rather than simply using the existing font family of one specific control. Using WPF What about WPF? WPF is a graphical subsystem you can use with the .NET Framework to build applications where the user interface is based on an XML language called XAML and the code is separate from the design and is based on a .NET language like Visual Basic.  In WPF, Microsoft changed the process yet again. Heres the way you do the same thing in WPF. Private Sub BoldCheckbox_Checked( _ByVal sender As System.Object, _ByVal e As System.Windows.RoutedEventArgs) _Handles BoldCheckbox.CheckedIf BoldCheckbox.IsChecked True ThenTextToBeBold.FontWeight FontWeights.BoldElseTextToBeBold.FontWeight FontWeights.NormalEnd IfEnd Sub The changes are: The CheckBox event is Checked instead of CheckedChangedThe CheckBox property is IsChecked instead of CheckStateThe property value is a Boolean True/False instead of the Enum CheckState. (Windows Forms offers a True/False Checked property in addition to CheckState, but WPF doesnt have both.)FontWeight is a dependency property of the Label instead of FontStyle being the property of the Font object.FontWeights is a NotInheritable class and Bold is a Static value in that class Whew!!  Do you think Microsoft  actually tried to make it more confusing?

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.