2

I'm writing a WPF app with VS2015. I have a User Control that contains an Image control. I have my image on the file system in an Images subfolder. In the Design mode, the image showed up fine, but when I ran it, it didn't. I specified the image location thus:

Source="Images/ball.png"

within the Image tag. I tried all the obvious things, like copying the folder to the bin\Debug folder and such. Experimenting, this error message popped up over the Source tag:

"Could not find a part of the path 'C:\Program Files (x86)\New folder\Microsoft Visual Studio 14.0\Common7\IDE\Images\red-ball.png'"

I finally got it to show up by giving it the FULL PATH to the image, but I really don't think I should have to. Isn't there a way to give it a relative path that's relative to the application and not the location of the IDE?

Frecklefoot
  • 1,660
  • 2
  • 21
  • 52

1 Answers1

2

First, make sure that your Images subfolder is relative to your project ie:

  • Project
    • Images
      • ball.png

Then with "ball.png" added to your project, set its Build Action to "Resource". Your link will now work as you expect.

I'm guessing its looking for the image in the place you mentioned because it couldn't find it in the resources where it wants to look. Note that sounds and video clips do not work this way, you have to copy those to your build output or use a pack URI.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • Okay, I had the image on the file system, but not included in the Solution. I don't know why that should matter, but after adding it to the solution, it found it fine. Thanks for the help! – Frecklefoot Sep 16 '16 at 00:51
  • 1
    @Frecklefoot It matters because by adding it to the solution and making it a resource, the compiler is actually embedding it in your EXE and the application can now find it. – BradleyDotNET Sep 16 '16 at 00:57
  • Does this mean you can't dynamically load an image from the file system and embed it in an image control? Or does an image from the file system have be loaded via code (not XAML)? – Frecklefoot Sep 16 '16 at 02:09
  • 1
    @Frecklefoot Of course you can. The path you give in XAML is interpreted as an URI, which can be a [Resource File Pack URI](https://msdn.microsoft.com/en-us/library/aa970069(v=vs.110).aspx) (when the path references a resource file), where the `pack://application:,,,` prefix is added automatically, but can also be a relative or absolute file URI, or a web URI. – Clemens Sep 16 '16 at 06:55
  • 1
    @Frecklefoot Typically images from the file system are loaded via code (using BitmpaImage) but it certainly *can* be done in XAML as Clemens pointed out – BradleyDotNET Sep 16 '16 at 16:33