简体   繁体   中英

Change the FontStyle in code behind in WPF

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

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

and I got error, any idea?

它是FontStyles.Italic ...使用FontStyles枚举来设置FontStyle的值

listBoxItem.FontStyle = FontStyles.Italic;

试试这个FontStyles.Italic

listBoxItem.FontStyle = FontStyles.Italic;

In this situation FontStyle is structure MSDN :

Defines a structure that represents the style of a font face 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 field _style of type Int . To set the value of Int type , it is taken from the static class FontStyles :

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, to setting FontStyle need to refer to a static class FontStyles :

SomeControl.FontStyle = FontStyles.Italic;

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

namespace MS.Internal.Text.TextInterface

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

This enumeration are Internal and I think used inside the system in conjunction with an public structure FontStyles .

namespace System.Drawing

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

This flags enumeration is Public and used in System.Drawing like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM