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.

Share:
50,194
tete
Author by

tete

Updated on January 16, 2020

Comments

  • tete
    tete over 3 years

    I 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 exception

    Cannot 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
    tete almost 11 years
    Thank 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
    invalidusername over 9 years
    and yes, don't forget to do clean and rebuild.. as Buzz stated.. it is easy to miss that.. I did :)
  • j riv
    j riv almost 8 years
    hehe, 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
    Ed Bayiates about 7 years
    Incredible -- cleaning and rebuilding was the issue! I spent hours trying to figure this one out, thanks!
  • J King
    J King over 6 years
    Echoing what @jriv said, I had to include the file in my project, just having it in the file was not enough
  • user1040323
    user1040323 over 4 years
    When 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
    fartwhif over 4 years
    Oh 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
    Natan Fernandes over 2 years
    I'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!