为什么我不能在 wpf 的资源字典中使用我的静态资源?

问题描述

我使用 ResourceDictionary 设计了我的控件(单选按钮),如下所示:

//in SidebarMenuButtonTheme.xaml

<Style targettype="{x:Type custom:MenuItem}"
        x:Key="MenuButtonTheme">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate targettype="{x:Type custom:MenuItem}">
                <Grid Background="{TemplateBinding Background}">
                    <TextBlock x:Name="SidebarRadioButtonMenuText"
                                Text="{TemplateBinding Property=Content}"                             
                                Foreground="#7D8083"
                                FontSize="14.59"
                                FontFamily="{StaticResource NunitoBold}" />
                </Grid>               
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

当我定义 FontFamily 时,Source 工作得很好:例如

FontFamily="/UiDesign/Fonts/#Nunito"

但是当我使用 StaticResource 作为 FontFamily

FontFamily="{StaticResource NunitoBold}"

我在 UI 中收到此错误

enter image description here

错误为:MenuItem 类型的元素 [MenuItem] 无法显示


这就是我在 App.xaml 中声明字体资源的方式

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/UiDesign/Theme/SidebarMenuButtonTheme.xaml" />
        </ResourceDictionary.MergedDictionaries>

        <FontFamily x:Key="NunitoBold">/UiDesign/Fonts/Nunito-Bold.ttf#Nunito</FontFamily>
    </ResourceDictionary>
</Application.Resources>

我不知道为什么会出现错误,尽管在我输入 StaticResource 时智能感知可以工作:

enter image description here


但是当我在 FontFamily定义我的 ResourceDictionary 资源时,菜单项将显示得很好。

//I added this above my Style tag...
<FontFamily x:Key="NunitoBold">/UiDesign/Fonts/Nunito-Bold.ttf#Nunito</FontFamily>

更新: 但是,当我在 StaticResource 中使用 UserControl(用于字体)时,我可以很好地使用它。我的问题是,我可以在 ResourceDictionay 中使用 App.xaml 中的资源吗?

解决方法

尝试使用 pack URI 引用字体:

<FontFamily x:Key="NunitoBold">pack://application:,/UiDesign/Fonts/Nunito-Bold.ttf#Nunito</FontFamily>

您还需要确保路径正确,即 UiDesign 是项目根目录下的文件夹,其中包含带有字体的 Fonts 文件夹。

,

我已经找到了解决方案,我没有使用 StaticResource,而是使用了 DynamicResource。现在我可以从 App.xaml 访问我的字体到我的 ResourceDictionary

相关问答

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