Wednesday, June 11, 2008

<Image Source="images/myimage.jpg" /> in WPF

I had a very annoying problem when I did a simple WPF program. I just wanted to test something and I wanted my program to display an image. This is what I did:

1. Create a new WPF application in Visual Studio.

2. Create a folder in my project with the name "images". Add an image to this folder on disk.

3. Right click the images-folder and select add existing item. The image is added and it is set to "Resource".

4. In Window1.xaml set the following code:

<Window x:Class="TestProject.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TestProject"
    Title="Test" Height="500" Width="650">

    <Grid Background="Black">
        <Image Source="images/1.jpg" />        
    </Grid>

</Window>

5. When running this code it works ok, but when I want to see it in the Visual Studio Designer I get an exception saying:

Error    1    The file /images/1.jpg is not part of the project or its 'Build Action' property is not set to 'Resource'.   

Solution: Rename the image to something like img1.jpg. I do not know why this happen but it works if you rename the image-file. You could rename it to 2.jpg and it will work. Anyone?

8 comments:

Anonymous said...

Thanks for the post! I couldn't see what I was doing wrong with such a simple task but it was Visual Studio all along ;)

Anonymous said...

A restart of VS also helps.

Anonymous said...

Also noticed that VS complains about Source="images/myimage.jpg" although the image is found at runtime.
Prefixing with "/" (Source="/images/myimage.jpg") fixed the problem for me.

Anonymous said...

Thank you!!!!!

I was trying the Windows Presentation Foundation Unleashed book and met this error. Changed file name of pinHorizontal.gif (as stated in the book) to pinHoriz.gif - worked straight away.

Alex said...

Brilliant! Renaming the file worked for me too. Tried everything, including slashes in the source URL, etc.

Adronius said...

Heh, I had the same problem and I wasn't able to find a solution till now. Thanks.

Unknown said...

Thank you Adrian F. The "/" solved my issue!

Unknown said...

Thank you Adrian F!
The trick with adding "/" solved my issue.