【问题标题】:Why can't I use my static resource in a resource dictionary in wpf?为什么我不能在 wpf 的资源字典中使用我的静态资源?
【发布时间】:2021-05-20 12:02:04
【问题描述】:

我使用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>

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

FontFamily="/UiDesign/Fonts/#Nunito"

但是当我使用StaticResource 作为FontFamily

FontFamily="{StaticResource NunitoBold}"

我在 UI 中收到此错误:

(错误为:无法显示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 时智能感知工作正常:


但是当我在ResourceDictionary 中定义我的FontFamily 资源 时,菜单项将正常显示。

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

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

【问题讨论】:

  • 要解决这个问题,我们需要查看您的解决方案资源管理器结构。可以给我看看吗?
  • @james.lee 我的帖子中缺少一些信息,我现在更新了...
  • 将你的 fontfamily 声明移动到你的资源字典中,在你引用它之前。
  • @Andy 我这样做了,它可以工作,但是当我在 App.xaml 中声明 fontfamily 时,fontfamily 将不适用(即使智能感知识别它)
  • @Andy 我需要在我的每个资源字典中创建一个“fontfamily”资源吗?

标签: wpf xaml resourcedictionary staticresource


【解决方案1】:

尝试使用pack URI 引用字体:

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

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

【讨论】:

  • 这也不起作用,给我一个错误:在“System.Windows.Markup.StaticResourceHolder”上提供值引发了异常。我知道我有正确的文件夹路径,因为智能感知识别了“NunitoBold”x 键
  • 如果您收到该错误,则表示您正在尝试引用无法找到的资源。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多