在代码中设置WPF图像源

I'm trying to set a WPF image's source in code. 我正在尝试在代码中设置WPF图像的源代码。 The image is embedded as a re
摘要由CSDN通过智能技术生成

本文翻译自:Setting WPF image source in code

I'm trying to set a WPF image's source in code. 我正在尝试在代码中设置WPF图像的源代码。 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;

The icon is defined something like this: <Image x:Name="_icon" Width="16" Height="16" /> 图标的定义如下: <Image x:Name="_icon" Width="16" Height="16" />


#1楼

参考:https://stackoom.com/question/1T3b/在代码中设置WPF图像源


#2楼

Here is an example that sets the image path dynamically (image located somewhere on disc rather than build as resource): 下面是一个动态设置图像路径的示例(图像位于光盘上的某个位置而不是构建为资源):

if (File.Exists(imagePath))
{
    // Create image element to set as icon on the menu element
   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值