Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

c# - Not able to reference Image source with relative path in xaml

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:MyAppImagesFolder-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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...