C# – Storing WPF Image Resources


For a WPF application which will need 10 – 20 small icons and images for illustrative purposes, is storing these in the assembly as embedded resources the right way to go?

If so, how do I specify in XAML that an Image control should load the image from an embedded resource?

Best Answer

If you will use the image in multiple places, then it's worth loading the image data only once into memory and then sharing it between all Image elements.

To do this, create a BitmapSource as a resource somewhere:

<BitmapImage x:Key="MyImageSource" UriSource="../Media/Image.png" />

Then, in your code, use something like:

<Image Source="{StaticResource MyImageSource}" />

In my case, I found that I had to set the Image.png file to have a build action of Resource rather than just Content. This causes the image to be carried within your compiled assembly.