【问题标题】:Included font does not load from resource dictionary in WPF包含的字体不会从 WPF 中的资源字典中加载
【发布时间】:2020-09-22 12:47:16
【问题描述】:

在我的 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>

我想将多个资源字典文件中的样式分开来组织我的应用程序文件。

如果有任何帮助,我将不胜感激

【问题讨论】:

  • 您是否尝试在 TextBlock.xaml 文件中定义 FontFamily?

标签: c# wpf xaml resourcedictionary app.xaml


【解决方案1】:

Style中改为DynamicResource

 <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>

【讨论】:

  • 更改为 DynamicResource 解决了我的问题。谢谢
猜你喜欢
  • 2018-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-02
相关资源
最近更新 更多