【发布时间】:2019-12-07 23:52:11
【问题描述】:
我正在尝试设置图像源,以最终从 DLL 引用中提取企业标准图像。
为了测试和确保 Uri 的正确语法,图像在本地加载到测试项目,源代码在 XAML 中硬编码。
<Image Name="imgTest" Source="pack://application:,,,/test2;component/Dictionaries/bricks.png"/>
在调试模式下查看了imgTest.Source的硬编码值:
imgTest.Source = "pack://application:,,,/test2;component/Dictionaries/bricks.png"
接下来,在代码中设置图像的来源。
BitmapImage imageUri = new BitmapImage();
imageUri.BeginInit();
var imageSource = new Uri(@"pack://application:,,,/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/" + "Dictionaries/bricks.png", UriKind.Absolute);
imageUri.UriSource = imageSource;
imageUri.EndInit();
imgCopy.Source = imageUri;
在调试模式下查看了imgTest.Source的软编码值:
imgTest.Source = "pack://application:,,,/test2;component/Dictionaries/bricks.png"
硬编码值和软编码值相同,但图像不使用软编码配置进行渲染。
已尝试使用嵌入式资源、内容和资源以及可用于“复制到输出目录”属性的三个选项中的每一个来更新图像的“构建操作”属性。
非常感谢您对此问题的任何智慧。
编辑#1
我将 Source 属性复制到软编码图像的并排比较产生没有显示图像,而硬编码图像尚未调试显示相同的 Source 值。显示 XAML 和 C# 代码。
<Image Name="imgCopy_Soft" />
<Image Name="imgCopy_Hard" Source="Dictionaries/bricks.png" />
imgCopy_Soft.Source = imgCopy_Hard.Source;
编辑#2这是完整的 XAML
<UserControl x:Class="test2.ucConfigurator"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:test2"
mc:Ignorable="d" Height="439.5" Width="400">
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="32"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="32"/>
<ColumnDefinition Width="32"/>
</Grid.ColumnDefinitions>
<Image Name="imgCopy_Soft" Grid.Column="0" />
<Image Name="imgCopy_Hard" Grid.Column="1" Source="pack://application:,,,/test2;component/Dictionaries/bricks.png" />
</Grid>
</Grid>
</UserControl>
以及它背后的代码:
namespace test2
{
public partial class ucConfigurator : UserControl
{
public ucConfigurator()
{
InitializeComponent();
}
public void Initialize()
{
BitmapImage imageUri = new BitmapImage();
imageUri.BeginInit();
var imageSource = new Uri(@"pack://application:,,,/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/" + "Dictionaries/bricks.png", UriKind.Absolute);
imageUri.UriSource = imageSource;
imageUri.EndInit();
imgCopy_Soft.Source = imageUri;
imgCopy_Soft.Source = imgCopy_Hard.Source;
}
}
}
【问题讨论】:
-
您是将 DLL 与 exe 一起提供还是尝试将 DLL 嵌入到 exe 中?
-
什么类型的 DLL 保存图像?它是 C# 资源库还是 C# 用户控件库?
-
确保
bricks.png是构建名为test2的程序集的VS 项目中项目文件夹Dictionaries中的一个文件。文件的 Build Action 必须是Resource。Copy to Output Directory设置无关紧要,因为构建操作Resource会生成“程序集资源”,即包含在程序集文件中的文件。如果test2不是您执行代码的程序集,还要确保它被引用。 -
DLL 最终会嵌入到 .exe 中。此时的测试不依赖于 DLL 引用。 png图片已经直接加载到测试项目中了。
-
对我来说,第一步是尝试找出为什么相同的 Uri 源定义的行为不同。硬代码版本显示图像,而软代码版本不显示。如果我能解决这个问题,基于已经完成的研究,嵌入式 DLL 工作应该不会带来任何额外的麻烦