本文翻译自: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