I come from a mostly web and a little bit Windows Forms background. For a new project, we will be using WPF. The WPF application will need 10 - 20 small icons and images for illustrative purposes. I am thinking about storing these in the assembly as embedded resources. Is that the right way to go?
How do I specify in XAML that an Image control should load the image from an embedded resource?
In code to load a resource in the executing assembly where my image
Freq.png
was in the folderIcons
and defined asResource
:I also made a function:
Usage (assumption you put the function in a ResourceHelper class):
Note: see MSDN Pack URIs in WPF:
pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml
Full description how to use resources: WPF Application Resource, Content, and Data Files
And how to reference them, read "Pack URIs in WPF".
In short, there is even means to reference resources from referenced/referencing assemblies.
If you're using Blend, to make it extra easy and not have any trouble getting the correct path for the Source attribute, just drag and drop the image from the Project panel onto the designer.
Some people are asking about doing this in code and not getting an answer.
After spending many hours searching I found a very simple method, I found no example and so I share mine here which works with images. (mine was a .gif)
Summary:
It returns a BitmapFrame which ImageSource "destinations" seem to like.
Use:
Method:
Learnings:
From my experiences the pack string is not the issue, check your streams and especially if reading it the first time has set the pointer to the end of the file and you need to re-set it to zero before reading again.
I hope this saves you the many hours I wish this piece had for me!
Yes, it is the right way.
You could use the image in the resource file just using the path:
You must set the build action of the image file to "Resource".
The following worked and the images to be set is resources in properties: