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.
I have noticed you don’t monetize your site, don’t waste your traffic, you can earn additional cash every month.
You can use the best adsense alternative for any type of website (they approve
all websites), for more info simply search in gooogle: boorfe’s tips
monetize your website
Hello, is anybody here interested in online working? It is simple survey filling.
Even $10 per survey (ten minutes duration). If you are interested, send me email to hansorloski[at]gmail.com
Very good. Really easy step by step guidance. This is my First WPF Application. Thanks
I was learning WPF from a book, but author never mentions the steps
to add image, thank god i found your post
Thanks, this was exactly what I was trying to do and had spent some time trying to find 🙂
Thanks. I am glad it helped. Don’t forget to like or +1 the post.