Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to reference Image source with relative path in xaml

Tags:

c#

wpf

I have created a ClassLibrary project, and added a xaml of Window type. I wrote a console application and showing this wpf window.

The problem is I have to show an Icon in this window.

If I am using following code it is not working

<Image Source="../Images/Folder-icon.png"></Image> 

When I give some hard coded path like

<Image Source="E:\MyApp\Images\Folder-icon.png"></Image> 

it works.

Why I have to give an hard coded path value? Is there any solution?

Hope I gave enough information. Please help I am struggling with this problem for more that 2 hours.

like image 348
user3013076 Avatar asked Sep 14 '14 16:09

user3013076


People also ask

How to set image source in Wpf XAML?

Here's how to set the source to an image from the app package. Image img = new Image(); BitmapImage bitmapImage = new BitmapImage(); Uri uri = new Uri("ms-appx:///Assets/Logo.png"); bitmapImage. UriSource = uri; img. Source = bitmapImage; // OR Image img = new Image(); img.


1 Answers

If Images folder is added in same project of its usage, this should work for you:

<Image Source="/Images/Folder-icon.png"/> 

Or use Pack Uri specifically:

<Image Source="pack://application:,,,/Images/Folder-icon.png"/> 

In case image resides in different project than current project where your XAML resides, you have to use more verbose definition of Pack URI where you have to specify the assembly name where image is added.

<Image Source="pack://application:,,,/Assembly;component/Images/Folder-icon.png"/> 

Replace Assembly with actual assembly name where image is added into.


Also make sure Build Action is set to Resource for file Folder-icon.png.


UPDATE:

More verbose definition of Pack URI works in sample as well. Try this out:

<Image Source="pack://application:,,,/ClassLibrary1;component/Folder-icon.png"/> 
like image 161
Rohit Vats Avatar answered Oct 14 '22 16:10

Rohit Vats