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.
- Open Visual Studio and go to File | New | Project.
- Select WPF Application.
- Provide a name and location.
- 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.
- Right-click on the project and choose Add | New Folder.
- Name the folder Images.
- Right-click on the Images folder and choose Add | Existing Item.
- Choose an image from your file system and click Add. Note: I used the sword.png image from my blog for this example.
- Right-click on your image file and choose Properties.
- Change the Build Action to Content.
- Change the Copy to Output Directory to Copy of Newer.
Step 3 – Add the image to XAML using a relative path URI
- 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.
- 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>
- 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.
- 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.