How to embed an image into your WPF application

If you are building an WPF application you could need images as background or as buttons or whatever. With your  first build or debug you will see the images will be stored in a folder that should not change. If you change it the application cannot find its images and crashes.
So if your installing this application you will need to make sure the pictures are in the exact place. There are possibilities to make the path of the path dynamic, but even that is not the best solution. 
So how to make sure your files will be where your application will be. 

The solution is to embed the images, but how..? Of course there are some hacks you need to know.

First of all you need to right click on your project in Visual Studio. Go to "Properties" and then "Resources". Add a resource and choose existing file. Choose your image.
The first step is done. Next click on the image and open its properties. Change the "Persistance" property into "embed in .ersx". 

Now go back into your Project Explorer, open up the Resources folder and choose your image. Go to "Properties" and choose "Resource" as "Build Action".

The last step is to go into your XAML and setup the image. If you are using an ImageBrush you should set the ImageSource to "pack://application:,,,/Resources/<YourImageName>.png". 

Now you can execute your builded executable after deleting the file in the resource folder and the application will still be able to display the image. Note: you will need the file to display it in debugging.

Comments

Popular posts from this blog

How to support multiple languages in WPF