如果我们使用StaticResource或DynamicResource,如何以pt为单位设置字体大小?

4

目前我正在使用字体大小资源作为

 <sys:Double x:Key="FontSize13">13</sys:Double>
<sys:Double x:Key="FontSize12">12</sys:Double>
<sys:Double x:Key="FontSize11">11</sys:Double>

并使用作为
        <Setter Property="FontSize"
            Value="{DynamicResource FontSize13}" />

如何将字体大小设置为点(如10pt)而不是像素?
3个回答

11

类型转换是由XAML编译器在编译时完成的,特别是响应于FontSize属性使用FontSizeConverter时进行的。因此,我们有一个基本问题无法使转换器运行。但是,我们可以创建一个帮助程序标记扩展来完成此任务。

以下是XAML的示例:

<Grid>
    <Grid.Resources>
        <local:FontSize Size="20" x:Key="TwentyPixels"/>
        <local:FontSize Size="11pt" x:Key="ElevenPoint"/>
    </Grid.Resources>
    <StackPanel>
        <TextBlock Text="Sample text" FontSize="{StaticResource TwentyPixels}"/>
        <TextBlock Text="Sample text" FontSize="{StaticResource ElevenPoint}"/>
    </StackPanel>
</Grid>

以下是标记扩展的代码:

public class FontSizeExtension : MarkupExtension
{
    [TypeConverter(typeof(FontSizeConverter))]
    public double Size { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return Size;
    }
}

没有扩展名,XAML 资源本身就无法实现这一点吗? - Kishore Kumar
我试图想出一种方法,但是无法做到。你可以像在静态资源中定义文本块并引用该字体大小那样做可怕的事情,但这不是你想要的。 - Rick Sladkey
感谢扩展方法。非常优秀。 - Kishore Kumar

-1

只需在数字和“pt”之间使用空格。例如:

<Style TargetType="TextBlock">
    <Setter Property="FontFamily" Value="Segoe UI"/>
    <Setter Property="FontSize" Value="11 pt"/>
</Style>

-3

将资源从Double更改为String,并包括单位说明符

<sys:String x:Key="FontSize13">13pt</sys:String>

1
很不幸,在运行时会抛出一个ArgumentException。 - M.Stramm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接