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;
The icon is defined something like this: <Image x:Name="_icon" Width="16" Height="16" />
There's also a simpler way. If the image is loaded as a resource in the XAML, and the code in question is the code-behind for that XAML content:
How to load an image from embedded in resource icons and images (corrected version of Arcturus):
Suppose you want to add a button with an image. What should you do?
Now it's time to load our image in XAML
Done.
You just missed a little bit.
To get an embedded resource from any assembly, you have to mention the assembly name with your file name as I have mentioned here:
This will load a image called "Untitled.png" in a folder called "Images" with its "Build Action" set to "Resource" in an assembly called "WpfApplication1".
This is a bit less code and can be done in a single line.
I am a new to WPF, but not in .NET.
I have spent five hours trying to add a PNG file to a "WPF Custom Control Library Project" in .NET 3.5 (Visual Studio 2010) and setting it as a background of an image-inherited control.
Nothing relative with URIs worked. I can not imagine why there is no method to get a URI from a resource file, through IntelliSense, maybe as:
I've tried a lot of URIs and played with ResourceManager, and Assembly's GetManifest methods, but all there were exceptions or NULL values.
Here I pot the code that worked for me: