WPF 如何在靜態資源定義字體大小


默認的 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>

這樣就可以在靜態資源里面定義字體大小

知識共享許可協議
本作品采用知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議進行許可。歡迎轉載、使用、重新發布,但務必保留文章署名林德熙(包含鏈接:http://blog.csdn.net/lindexi_gd ),不得用於商業目的,基於本文修改后的作品務必以相同的許可發布。如有任何疑問,請與我聯系


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM