默认的 wpf 的字体大小的单位是像素,如果想要将字体大小使用 pt 点表示,写在 xaml 里面是直接添加 pt 后缀。但是此时如果在静态资源尝试定义的时候写上了 pt 将会在运行的时候提示无法转换

默认的单位是 pixel 如下面代码写的

            <textblock margin="10,10,10,10"
                       fontsize="10"
                       text="林德熙是逗比"></textblock>
            <textblock margin="10,10,10,10"
                       fontsize="10pt"
                       text="林德熙是逗比"></textblock>

实际运行的效果可以看到使用 pt 的字体显然比 pixel 的大

这是在 xaml 写的,如果想要在资源里面写,如下面代码,将不能通过运行

    <window.resources>
        <system:string x:key="fontsize">10pt</system:string>
    </window.resources>
    <grid>
        <stackpanel verticalalignment="center" horizontalalignment="center">
            <textblock margin="10,10,10,10"
                       fontsize="10"
                       text="林德熙是逗比"></textblock>
            <textblock margin="10,10,10,10"
                       fontsize="{staticresource fontsize}"
                       text="林德熙是逗比"></textblock>
        </stackpanel>
    </grid>

原因是 fontsize 类是一个 double 类型,此时构建将提示不能将字符串转换为 double 类

an object of the type "system.string" cannot be applied to a property that expects the type "system.double".	celakercalbochallhinerjufeeqalchelfu	mainwindow.xaml	19	

但是为什么在 xaml 写在属性里面支持添加单位 pt 呢,原因是在 fontsize 属性标记特性 typeconverter 通过这个进行转换

按照这个方法,可以在本地定义一个专门的字体大小的类

using system.windows.markup;

public class fontsizeextension : markupextension
{
    [typeconverter(typeof(fontsizeconverter))]
    public double size { get; set; }

    public override object providevalue(iserviceprovider serviceprovider)
    {
        return size;
    }
}

将这个类放在代码,然后就可以在 xaml 资源写下面代码

    <window.resources>
        <local:fontsize x:key="fontsize" size="10pt"></local:fontsize>
    </window.resources>
    <grid>
        <stackpanel verticalalignment="center" horizontalalignment="center">
            <textblock margin="10,10,10,10"
                       fontsize="10"
                       text="林德熙是逗比"></textblock>
            <textblock margin="10,10,10,10"
                       fontsize="{staticresource fontsize}"
                       text="林德熙是逗比"></textblock>
        </stackpanel>
    </grid>

在使用 markupextension 可以忽略 extension 只写前面部分,也就是写的是 fontsize 在资源,换句话说,写 fontsizeextension 也没问题

    <window.resources>
        <local:fontsizeextension x:key="fontsize" size="10pt"></local:fontsizeextension>
    </window.resources>

这样就可以在静态资源里面定义字体大小

本作品采用进行许可。欢迎转载、使用、重新发布,但务必保留文章署名(包含链接: ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我。