在学习WPF时,经常看到如下路径使用的写法:
Images/IsNotMute.png
pack://application:,,,/WpfApplication1;component/Properties/../Images/IsNotMute.png
pack://application:,,,/WpfApplication1;component/Images/IsNotMute.png
pack://application:,,,/Images/IsNotMute.png
pack://SiteOfOrigin:,,,/Images/IsNotMute.png
Environment.CurrentDirectory+“/Images/IsNotMute.png”
下面以在后台给Image的Source赋值为例,来区分一下上述各种写法。
一、使用 解决方案中本项目下 Images文件夹下的图片 的相对路径
Uri uri = newUri("/WpfApplication1;component/Images/IsNotMute.png",UriKind.Relative);
image1.Source = newBitmapImage(uri);
可以简写为:
Uri uri =newUri("Images/IsNotMute.png",UriKind.Relative);
image1.Source = newBitmapImage(uri);
二、使用 解决方案中本项目下 Images文件夹下的图片 的绝对路径
Uri uri =newUri("pack://application:,,,/WpfApplication1;component/Properties/../Images/IsNotMute.png",UriKind.Absolute);
image1.Source = newBitmapImage(uri);
可简写为:
Uri uri =newUri("pack://application:,,,/WpfApplication1;component/Images/IsNotMute.png",UriKind.Absolute);
image1.Source = newBitmapImage(uri);
还也可简写为:
Uri uri =newUri("pack://application:,,,/Images/IsNotMute.png",UriKind.Absolute);
image1.Source = newBitmapImage(uri);
三、使用 解决方案中其他项目下 Images文件夹下的图片 的相对路径
[注意:当前项目要引用 存放资源的那个项目]
Uri uri =newUri("/WpfApplication2;component/Images/IsNotMute.png",UriKind.Relative);
image1.Source = newBitmapImage(uri);
四、使用 解决方案中其他项目下 Images文件夹下的图片 的绝对路径
[注意:当前项目要引用 存放资源的那个项目]
Uri uri =newUri("pack://application:,,,/WpfApplication2;component/Properties/../Images/IsNotMute.png",UriKind.Absolute);
image1.Source = newBitmapImage(uri);
可以简写为:
Uri uri =newUri("pack://application:,,,/WpfApplication2;component/Images/IsNotMute.png",UriKind.Absolute);
image1.Source = newBitmapImage(uri);
五、使用工程目录(Output文件夹)中Images文件夹下的图片(可以叫做源站点文件) 的绝对路径
Uri uri =newUri("pack://SiteOfOrigin:,,,/Images/IsNotMute.png",UriKind.Absolute);
image1.Source = newBitmapImage(uri);
六、使用工程目录(Output文件夹)中Images文件夹下的图片的绝对路径
Uri uri =newUri(Environment.CurrentDirectory + "/Images/IsNotMute.png",UriKind.Absolute);
image1.Source = newBitmapImage(uri);
注意:
Uri uri = newUri("……");该构造函数默认等同于
Uri uri = newUri("……",UriKind.Absolute);即视路径为绝对路径
如果不确定自己使用的路径 是相对路径还是绝对路径,可以使用UriKind.RelativeOrAbsolute。但是,在写程序时还是建议明确指定所用路径是UriKind.Relative还是UriKind.Absolute。
说明:
pack URI格式是XML文件规范的一部分,具体格式如下 pack://packageURI/partPath。
PackageURI实际上是在URI中放一个URI,它是把反斜杠都变成了逗号。
packageURI的WPF资源路径可以志向一个XPS文档,例如file : /// c: /Document . xps会被编码为file:...c:,Document.xps。
在WPF程序中有两种URI系统是特别处理的:
siteOfOrigin:///编码后siteOfOrigin:,,,
application:///编码后application:,,,
3个逗号其实是反斜杠编码过来的。
参考:http://blog.csdn.net/xbgprogrammer/article/details/44600617