In WPF, how to specify the path to a file nested in a directory using XAML?

I'm trying to do this ...

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

But I get this error ...

It is not possible to convert the string 'Images \ unlock.png' to the attribute 'Source' for an object of type 'System.Windows.Media.ImageSource'. Unable to find resource 'forms / images / unlock.png'. Error in the object "System.Windows.HierarchicalDataTemplate" in the markup file "Fuse; component / form / mainwindow.xaml" Line 273 Position 51.

As you can see, my form, which includes this XAML, is in a folder called Forms. My images are in the "Images" folder. How do I map from forms to images?

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

Any help?

+6
file path wpf xaml
source share
4 answers

Try a slash, not a backslash, and use an absolute path leading with a slash:

 Source="/Images/unlock.png" 

It generally works for me.

Otherwise, see Pack URI .

+9
source share
  • Add your image to the project in VS
  • Right click on this image unlock.png
  • Go to context menu / Properties
  • Change build action for resource

Here it is: -)

+5
source share

Have you tried to set the source to BitmapImage ?

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

I believe that the default Uri type for UriSource is a relative Uri that works with the base class of the application. Perhaps you can configure BitmapSource little easier than trying to find the exact way to enter the file path in the Source attribute.

0
source share

To use a resource located in a folder other than the one where your XAML is located, do the following:

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

Where Resources is the name of the directory from which you want to use resources, and image.png is the name of the displayed image. The answer was found thanks to @ matt-hamilton and @ brian-hinchey and their mention of the Pack URI.
Works great with your own converters. You just need to return the line matching scheme above.

0
source share

All Articles