7

I am trying to do this...

<Image x:Name="imgGroupImage" Source="Images\unlock.png" Margin="0,0,5,0" />

But I get this error...

Cannot convert string 'Images\unlock.png' in attribute 'Source' to object of type 'System.Windows.Media.ImageSource'. Cannot locate resource 'forms/images/unlock.png'. Error at object 'System.Windows.HierarchicalDataTemplate' in markup file 'Fuse;component/forms/mainwindow.xaml' Line 273 Position 51.

As you can see, my form that includes this XAML is in a folder named Forms. My Images are in a folder named Images. How do I map from Forms to Images?

I tried Source="..Images\unlock.png" which does not work in WPF.

Any help?

TobiMcNamobi
  • 4,687
  • 3
  • 33
  • 52
Doug
  • 1,991
  • 4
  • 25
  • 35

4 Answers4

9

Try slashes rather than backslashes, and use an absolute path by leading with a slash:

Source="/Images/unlock.png"

That generally works for me.

Failing that, take a look at Pack URIs.

Matt Hamilton
  • 200,371
  • 61
  • 386
  • 320
  • The Pack URI link is not working for me. This is an equivalent: https://msdn.microsoft.com/en-us/library/vstudio/aa970069(v=vs.100).aspx – Brian Hinchey Sep 09 '15 at 02:16
5
  1. Add your image to the Project in VS
  2. Right click on that image unlock.png
  3. Go to Context menu /Properties
  4. Change Build Action to Resource

Thats it :-)

Brian Deragon
  • 2,929
  • 24
  • 44
Jamal
  • 51
  • 1
  • 1
0

Have you tried setting the source to a BitmapImage?

<Image x:Name="imgGroupImage" Margin="0,0,5,0"  >
   <Image.Source>
      <BitmapImage UriSource="Images/unlock.png" />
   </Image.Source>
</Image>

I believe the default type of Uri for UriSource is a relative Uri, which works off the application's base class. You might find you can configure the BitmapSource a bit easier than trying to find the exact way you have to enter the file path in the Source attribute.

Brian Deragon
  • 2,929
  • 24
  • 44
0

In order to use resource located in folder different that the one where your XAML is, do this:

<Image Source="pack://application:,,,/Resources/image.png"/>

Where Resources is name of directory which you want to use resources from and image.png is name of image to display. Answer found thanks to @matt-hamilton and @brian-hinchey and their mention of Pack URI.
Works perfectly with your own Converters. You just have to return string matching schema above.

Hekkaryk
  • 522
  • 5
  • 13