簡體   English   中英

為什么我不能在 wpf 的資源字典中使用我的 static 資源?

[英]Why can't I use my static resource in a resource dictionary in 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>

當我定義Source時, FontFamily工作得很好:例如

FontFamily="/UiDesign/Fonts/#Nunito"

但是當我為FontFamily使用StaticResource

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 中的資源嗎?

嘗試使用包 URI引用字體:

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

您還需要確保路徑正確,即UiDesign是項目根目錄下的文件夾,其中包含字體的Fonts文件夾所在的位置。

我已經找到了解決方案,我沒有使用StaticResource ,而是使用了DynamicResource 現在我可以從App.xaml到我的ResourceDictionary

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM