Change FontStyle in code in WPF

How can I change the FontStyle in code in WPF. I tried this:

 listBoxItem.FontStyle = new FontStyle("Italic"); 

and I got an error, any idea?

+6
source share
3 answers

It was FontStyles.Italic ... Use the FontStyles enumeration to set the value for FontStyle

 listBoxItem.FontStyle = FontStyles.Italic; 
+10
source

Try FontStyles.Italic

 listBoxItem.FontStyle = FontStyles.Italic; 
+2
source

In this situation, FontStyle has an MSDN structure:

Defines a structure that represents the font style as normal, italic, or oblique.

It can be viewed in ILSpy :

 [TypeConverter(typeof(FontStyleConverter)), Localizability(LocalizationCategory.None)] public struct FontStyle : IFormattable { private int _style; internal FontStyle(int style) { this._style = style; } 

Here we see that the _style field _style type Int . To set a value of type Int , it is taken from the static FontStyles class:

 public static class FontStyles { public static FontStyle Normal { get { return new FontStyle(0); } } public static FontStyle Oblique { get { return new FontStyle(1); } } public static FontStyle Italic { get { return new FontStyle(2); } } internal static bool FontStyleStringToKnownStyle(string s, IFormatProvider provider, ref FontStyle fontStyle) { if (s.Equals("Normal", StringComparison.OrdinalIgnoreCase)) { fontStyle = FontStyles.Normal; return true; } if (s.Equals("Italic", StringComparison.OrdinalIgnoreCase)) { fontStyle = FontStyles.Italic; return true; } if (s.Equals("Oblique", StringComparison.OrdinalIgnoreCase)) { fontStyle = FontStyles.Oblique; return true; } return false; } } 

So, it turns out that to install FontStyle you need to refer to the static FontStyles class:

 SomeControl.FontStyle = FontStyles.Italic; 

It can be a bit confusing, in fact there are two FontStyle (without s) enums:

namespace MS.Internal.Text.TextInterface

 internal enum FontStyle { Italic = 2, Oblique = 1, Normal = 0 } 

This enumeration is internal, and I think that it is used internally in conjunction with the FontStyles public structure.

namespace System.Drawing

 [Flags] public enum FontStyle { Regular = 0, Bold = 1, Italic = 2, Underline = 4, Strikeout = 8 } 

This flag enumeration is publicly available and is used in System.Drawing as follows:

 SomeControl.Font = new Font(FontFamily.GenericSansSerif, 12.0F, FontStyle.Bold | FontStyle.Italic); 
+1
source

All Articles