Monday, August 20, 2007

Using Project Resources in WPF

For a project I am working on, I have a directory full of icons that I use. I had been loading them from a fixed path on disk, but I wanted to make my application more portable so I decided to turn them into project resources.

To to this, you first create a folder in your project to store your resources. You can put them in the project root, but that gets cluttered. In my case, I created a new folder in my project called 'Icons'. Next, add your image files to the new folder. You can copy them directly to the folder and then import them into the project by using 'Add Existing Item'.

Once added, check the Properties of your images to ensure they have a Build Action of 'Resource' (they should be by default -- at least that is the behavior I get with Visual Studio 2008). Now when you build your project they will be compiled directly into the executable.

Referencing the embedded resources to create WPF images is simple. From XAML, you simply specify the relative path to the resource as your Image Source:

<Image Source="Icons/MyImage.png" />

From code, you specify the path as a relative URI:

Image myImage = new Image();
myImage.Source = new BitmapImage(new Uri("Icons/MyImage.png", UriKind.Relative));