【问题标题】:How to use resources (fonts, images, styles) from external library如何使用外部库中的资源(字体、图像、样式)
【发布时间】:2020-06-05 19:40:10
【问题描述】:

我在从外部资源 dll 加载资源(图像、字体系列、样式)时遇到问题。我想将所有资源(图像、字体、样式...)放在一个资源 dll 中,并将它们设置为可在此解决方案中的所有项目(库)中访问。解决方案中的那些项目是由主应用程序引用和调用的不同库。

到目前为止,我尝试了几种不同的建议,但都没有奏效。 我正在使用 Visual Studio 2019 并为 .net 4.6.2 进行编译 - 如果这意味着什么...

首先,我创建了一个名为 myapp.resources 的资源库。在这个项目中,我有一个名为 Fonts 的文件夹,该文件夹中是 Lato-Thin 字体。

我还在项目的根目录中创建了一个名为 Fonts.xaml 的资源字典

-项目 -字体 -Lato-Thin.ttf -Fonts.xaml

Fonts.xaml 的结构:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:myapp.resources">

    <FontFamily x:Key="LatoThin">Fonts/#Lato Thin</FontFamily>    
</ResourceDictionary>

在主应用 App.xaml 中,我添加了该 ResourceDictionary 的加载:

<ResourceDictionary x:Key="Dict">
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/myapp.resources;component/Fonts.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>

最后一步是将此字体系列添加到标签控件中:

<Label Grid.Row="0" Grid.Column="0" Content="some random text for test" FontFamily="{StaticResource ResourceKey=LatoThin}"/>

但我总是得到LatoThin字体资源无法定位的错误。

与图像、样式等任何其他资源类型相同的错误。

当然,我添加了对项目的引用,每个文件都在它应该在的位置。

唯一有效的是,例如以这种方式将图像添加到按钮。

<syncfusion:ButtonAdv x:Name="btnSelectFile" 
                              Grid.Row="1" Grid.Column="2"
                              VerticalAlignment="Center" SizeMode="Small"
                              Height="26" Width="26" Label="Button" Margin="3,3,3,3"
                        SmallIcon="pack://application:,,,/myapp.resources;component/Images/add.png"/>

我试图找到一些完整的教程来学习,但我总是遇到同样的错误。

所以,我的问题是:如何解决这个问题?

感谢您的任何建议。

【问题讨论】:

    标签: c# wpf resources


    【解决方案1】:

    确保您的字体文件 (Lato-Thin.ttf) 的构建操作设置为 Resource

    确保在您的 Fonts.xaml 中使用这种格式:

    <ResourceDictionary 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:myapp.resources">
    
        <FontFamily x:Key="LatoThin">/myapp.resources;component/Fonts/#Lato Thin</FontFamily>
    
    </ResourceDictionary>
    

    提示:您可以从 URI 中删除 pack://application:,,, 以缩短它们。

    【讨论】:

    • 感谢您的回答,但仍然没有。该应用程序没有给出任何错误,但标签仍以默认字体显示。我尝试在几个地方设置 FontFamily 属性,但没有任何变化。即使在设计时,如果我没记错的话,智能感知会显示字体系列,还是不显示?因为,如果我没记错的话,在第一次重建后智能感知应该显示字体名称,但当我在 FontFamily=""... 输入 xaml 时不显示任何内容
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    相关资源
    最近更新 更多