WPF throws "Cannot locate resource" exception when loading the image
50,194
In Solution Explorer set the image file's Build Action property to Resource. Then clean the solution and rebuild it.
Author by
tete
Updated on January 16, 2020Comments
-
tete over 3 yearsI am having a WPF window, with a background image of one file in my local system. So the XAML file looks like this:
<Window.Background> <ImageBrush ImageSource="/MYASSEMBLY;component/Resources/MyPic.png"/> </Window.Background>In the XAML designer it actually shows this background image, so the image does exist in MYASSEMBLY\Resources folder. However, in the
InitializeComponent()function call when I launch the application, it throws the exceptionCannot locate resource 'resources/mypic.png'.
So I am totally lost now. Are the directories different between the design and runtime so doesn't exist in the runtime?
-
tete almost 11 yearsThank you, that solves the problem. I thought it would load the picture in the runtime so I didn't even include the image into the project. -
invalidusername over 9 yearsand yes, don't forget to do clean and rebuild.. as Buzz stated.. it is easy to miss that.. I did :) -
j riv almost 8 yearshehe, most of us, including the op, didn't really have that property issue, but we didn't expect that it's required to have the image in the solution explorer if it's already in the physical directory. It's pretty cool to be honest that it's required in the explorer. Thanks! -
Ed Bayiates about 7 yearsIncredible -- cleaning and rebuilding was the issue! I spent hours trying to figure this one out, thanks! -
J King over 6 yearsEchoing what @jriv said, I had to include the file in my project, just having it in the file was not enough -
user1040323 over 4 yearsWhen you access an image like this <ImageBrush ImageSource="/Resources/bigWaves.png" /> it seems to work OK. But if the Window is in a WPF Control Library and is actually run from a WinForms project it breaks. My solution was to change the path to: <ImageBrush ImageSource="Resources/bigWaves.png" /> The images should automatically be set with a Resource build action as soon as they're added to the project. -
fartwhif over 4 yearsOh VS... now I have to clean upon every build to clear the false errors, see my control in designer, and cure XAML of its squiggle disease. -
Natan Fernandes over 2 yearsI'm here 9 years later this is the only answer for this problem I could find in the entire StackOverflow community, including other languages. Thank you!