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));

7 comments:

  1. Thanks Mike, that's the simplest way of getting an image from the application's resources I've seen.

    Good on ya!

    ReplyDelete
  2. Just FYI. I had to add a forward slash to make it work -

    ReplyDelete
  3. Thanks Anonymous, yes it didnt work for me either, and adding the leading forward slash did the trick, THANKS.

    ReplyDelete
  4. Its work for me !

    Sleepimg.Source = New BitmapImage(New System.Uri("/WpfApplication8;component/Images/LH1 - Shutdown.png", UriKind.Relative))

    this work if u want change ur standard image and to give it a new picture after any Event like button_click,moveOver ..

    ReplyDelete
  5. Adding / before folder name did the trick!!!
    Thanks both!

    ReplyDelete
  6. Adding slash before folder name solves the problem but creates another problem in design view. Shows error "Invalid URI: The format of the URI could not be determined."

    ReplyDelete