在代码中设置 WPF 图片源 [英] Setting WPF image source in code

查看:23
本文介绍了在代码中设置 WPF 图片源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在代码中设置 WPF 图像的源.图像作为资源嵌入到项目中.通过查看示例,我想出了以下代码.由于某种原因它不起作用 - 图像不显示.

I'm trying to set a WPF image's source in code. The image is embedded as a resource in the project. By looking at examples I've come up with the below code. For some reason it doesn't work - the image does not show up.

通过调试我可以看到流包含图像数据.怎么了?

By debugging I can see that the stream contains the image data. So what's wrong?

Assembly asm = Assembly.GetExecutingAssembly();
Stream iconStream = asm.GetManifestResourceStream("SomeImage.png");
PngBitmapDecoder iconDecoder = new PngBitmapDecoder(iconStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
ImageSource iconSource = iconDecoder.Frames[0];
_icon.Source = iconSource;

图标定义如下:<Image x:Name="_icon" Width="16" Height="16"/>

推荐答案

在遇到和你一样的问题并阅读了一些资料后,我找到了解决方案 - 打包 URI.

After having the same problem as you and doing some reading, I discovered the solution - Pack URIs.

我在代码中做了以下事情:

I did the following in code:

Image finalImage = new Image();
finalImage.Width = 80;
...
BitmapImage logo = new BitmapImage();
logo.BeginInit();
logo.UriSource = new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png");
logo.EndInit();
...
finalImage.Source = logo;

或者更短,通过使用另一个 BitmapImage 构造函数:

Or shorter, by using another BitmapImage constructor:

finalImage.Source = new BitmapImage(
    new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png"));

URI 被分成几个部分:

The URI is broken out into parts:

  • 权限:application:///
  • Path:编译成引用程序集的资源文件的名称.路径必须符合以下格式:AssemblyShortName[;Version][;PublicKey];component/Path

  • AssemblyShortName:引用程序集的短名称.
  • ;Version [可选]:包含资源文件的引用程序集的版本.这用于加载两个或多个具有相同短名称的引用程序集.
  • ;PublicKey [可选]:用于对引用的程序集进行签名的公钥.这用于加载两个或多个具有相同短名称的引用程序集.
  • ;component:指定被引用的程序集是从本地程序集引用的.
  • /Path:资源文件的名称,包括其路径,相对于引用程序集的项目文件夹的根目录.

application: 后面的三个斜杠必须用逗号代替:

The three slashes after application: have to be replaced with commas:

注意:pack URI 的权限组件是一个嵌入的 URI,指向一个包并且必须符合 RFC 2396.此外,/"字符必须替换为,"字符,和保留字符,例如%"和 "?"必须逃脱.见 OPC详情.

Note: The authority component of a pack URI is an embedded URI that points to a package and must conform to RFC 2396. Additionally, the "/" character must be replaced with the "," character, and reserved characters such as "%" and "?" must be escaped. See the OPC for details.

当然,请确保将图像上的构建操作设置为 Resource.

And of course, make sure you set the build action on your image to Resource.

这篇关于在代码中设置 WPF 图片源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆