简体   繁体   中英

Why can't I use my static resource in a resource dictionary in wpf?

I designed my control (radio button) using a ResourceDictionary like this:

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

The FontFamily works just fine when I define the Source : eg

FontFamily="/UiDesign/Fonts/#Nunito"

But when I use StaticResource for the FontFamily

FontFamily="{StaticResource NunitoBold}"

I receive this error in my UI:

在此处输入图像描述

(The error is: The element [MenuItem] of type MenuItem could not be displayed)


This is how I declare my font resource in my 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>

I don't know why this is giving an error, even though intellisense works when I type StaticResource :

在此处输入图像描述


But when I define my FontFamily resource in the ResourceDictionary , the menu items will display just fine.

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

Update: But, when I use the StaticResource (for the font) in a UserControl , I can use it just fine. My problem here is that, can I use the resource in App.xaml, in a ResourceDictionay?

Try to reference the font using a pack URI :

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

You also need to ensure that the paths is correct, ie that UiDesign is a folder at the root of your project in which the Fonts folder with the font is located.

I already found a solution for this, instead of using StaticResource I used DynamicResource instead. Now I can access my fonts from App.xaml to my ResourceDictionary .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM