包含的字体不会从WPF中的资源字典加载

问题描述

在我的WPF应用程序中,我在App.xaml文件包括了正在使用的字体,如下所示:

<Application x:Class="STFAPP.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:STFAPP"
         StartupUri="Views/LoginWindow.xaml">
<Application.Resources>
    <ResourceDictionary>
        <!--Included Fonts-->
        <FontFamily x:Key="TheSans">pack://application:,/Style/Fonts/#TheSans</FontFamily>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Style/TextBlock.xaml"></ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

TextBlock.xaml是一种资源字典,包含TextBlock样式:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Style targettype="{x:Type TextBlock}" x:Key="TitleStyle">
    <Setter Property="FontFamily" Value="{StaticResource TheSans}" />
    <Setter Property="FontSize" Value="15" />
</Style>

我在TextBlock中使用了以下样式:

<TextBlock Text="Hello" Style="{StaticResource TitleStyle}"/>

字体未加载!?

如果我避免使用单独的资源字典(TextBlock.xaml文件)并将样式直接粘贴到App.xaml,则字体将成功加载:

<Application x:Class="STFAPP.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:STFAPP"
         StartupUri="Views/LoginWindow.xaml">
<Application.Resources>
    <ResourceDictionary>
        <!--Included Fonts-->
        <FontFamily x:Key="TheSans">pack://application:,/Style/Fonts/#TheSans</FontFamily>

        <Style targettype="{x:Type TextBlock}" x:Key="TitleStyle">
            <Setter Property="FontFamily" Value="{StaticResource TheSans}" />
            <Setter Property="FontSize" Value="15" />
        </Style>

    </ResourceDictionary>
</Application.Resources>

我想在多个资源字典文件中分离样式以组织我的应用程序文件

感谢您的帮助

解决方法

DynamicResource中更改为Style

 <Setter Property="FontFamily" Value="{DynamicResource TheSans}" />

或者将FontFamily资源移动到TextBlock.xaml或其他资源字典中,例如Fonts.xaml,然后将其合并:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Style/Fonts.xaml" />
            <ResourceDictionary Source="Style/TextBlock.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...