在code设置WPF图像源 [英] Setting WPF image source in code

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

问题描述

我想设置code一个WPF图像的来源。的图像嵌入作为项目的资源。通过查看例子,我拿出低于code。出于某种原因,这是行不通的 - 图像不显示。

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;

该图标的定义是这样的:<图像X:名称=_图标WIDTH =16高度=16/>

推荐答案

有同样的问题,因为你和做一些阅读后,我发现了解决方案 - 的包的URI

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

我做了以下在code:

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;

的URI被分为部分:

The URI is broken out into parts:

  • 授权:应用程序:///
  • 路径:一个资源文件被编译成一个引用的程序集的名称。该路径必须符合以下格式: AssemblyShortName [;版本] [;公钥];组件/路径

  • AssemblyShortName:短名称引用的程序集
  • ;版本[可选]:引用的程序集包含资源文件的版本。这是用来当加载两个或多个引用的程序使用相同的短名称。
  • ;公钥[可选]:这是用来签署引用的程序集的公钥。这是用来当加载两个或多个引用的程序使用相同的短名称。
  • ;部分:指定组件被称为是从当地组装引用
  • /路径:资源文件的名称,包括它的路径,相对于引用的程序集的项目文件夹的根目录

申请后的三个斜杠:已替换为逗号:

注:一包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.

当然,一定要设置在图像生成操作,以资源

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

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

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