Using relative path images included as content with WPF

Many people want to include an image but for reasons such as the ability to change branding, the image should not be compiled in.

Step 1 – Create a new WPF Application project

For most, you don’t need steps to create a project, but just in case you are creating a WPF project for the first time, here are the steps.

  1. Open Visual Studio and go to File | New | Project.
  2. Select WPF Application.
  3. Provide a name and location.
  4. Click OK.

Step 2 – Add an image as Content to the project

Were are going to create a folder called images and put the image there.

  1. Right-click on the project and choose Add | New Folder.
  2. Name the folder Images.
  3. Right-click on the Images folder and choose Add | Existing Item.
  4. Choose an image from your file system and click Add. Note: I used the sword.png image from my blog for this example.
  5. Right-click on your image file and choose Properties.
  6. Change the Build Action to Content.
  7. Change the Copy to Output Directory to Copy of Newer.

Step 3 – Add the image to XAML using a relative path URI

  1. Change the Window to size to content and added a MinWidth and MinHeight as shown on lines 5 and 6. Note: This step wasn’t required, but I did it.
  2. Add an image to the MainWindow.xaml as shown on line 8.
    <Window x:Class="RelativePathImages.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" 
            SizeToContent="WidthAndHeight"
            MinHeight="200" MinWidth="300">
        <Grid>
            <Image />
        </Grid>
    </Window>
    
  3. Configure the Source of the image to be the relative path using a Pack URI. See this article on MSDN for more information on Pack URIs: Pack URIs in WPF
        <Grid>
            <Image Source="pack://siteoforigin:,,,/Images/Sword.png" MaxWidth="1024"/>
        </Grid>
    

    Note: I also added a MaxWidth to the image because the resolution was huge.

  4. Build and run your project.

Your image is now loaded from whatever image is located in the relative path from your executable. Note: Another option for doing this includes using a ViewModel and binding.

4 Comments

  1. Praveen says:

    Very good. Really easy step by step guidance. This is my First WPF Application. Thanks

  2. prash says:

    Hi

    I was learning WPF from a book, but author never mentions the steps
    to add image, thank god i found your post

    regards
    prash

  3. Steve says:

    Thanks, this was exactly what I was trying to do and had spent some time trying to find 🙂

Leave a Reply

*