WPF中的嵌入的资源与Resource
我们将资源文件添加至.net C#工程时,文件的生成操作有多种可选方式。通常用的多的是两种:[嵌入的资源]和[Resource],如果从需要从代码中使用这些资源文件,不同生成操作则对应不同的引用方式:
[嵌入的资源]
Assembly assembly = Assembly.GetAssembly(typeof(App));
var stream = assembly.GetManifestResourceStream("WpfApp1.Resources.XMLFile1.xml");
[Resource]
var uristr = "pack://application:,,,/WpfApp1;component/Resources/XMLFile2.xml";
var uri = new Uri(uristr, UriKind.RelativeOrAbsolute);
var stream = Application.GetResourceStream(uri).Stream;
实现示例:
[嵌入的资源]
string name = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + "."+fileName;
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream stream = assembly.GetManifestResourceStream(name);
[Resource]
var uristr = "/Documents/"+ fileName; //file资源放在Documents文件夹下
var uri = new Uri(uristr, UriKind.Relative);
var stream = Application.GetResourceStream(uri).Stream;
注:在同一个程序集内部调用资源,可以省掉pack://application:,,,/WpfApp1;component
,
C# Uri
Uri表达式的一般形式为:协议+授权+路径
协议:pack://
授权:有两种。一种用于访问编译时已经知道的文件,用application:///
一种用于访问编译时不知道、运行时才知道的文件,用siteoforigin:///
一般用逗号代替斜杠,也就是改写作application:,,,
和pack:,,,
路径:分为绝对路径和相对路径。一般选用相对路径,普适性更强。
装载图片的两种方式,一种用XAML引用资源,一种用代码引用资源。
用XAML引用资源:
<Image Source="pack://application:,,,/images/my.jpg"/>
也可以这样
<Image Source="/images/my.jpg"/>
用代码引用资源:
Image img;
img.Source=new BitmapImage(new Uri("pack://application:,,,/images/my.jpg"),UriKind.Relative);
也可以直接使用代码中引用图片资源:
image2.Source = new BitmapImage(new Uri("/images/my.jpg", UriKind.Relative));
WPF 调用资源图片
imagePath = "pack://application:,,,/Solution;component/Properties/../images/star/my.jpg";
imageBrush.ImageSource = new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute));
WPF引用外部项目资源的方法
WPF中如果你使用的资源文件不是本程序集的,是另外的程序集,就可以这样做:
1.引用要用的程序集,pack://application:,,,/程序集名称;component/路径
,其中pack://application:,,,
可以省略
示例:
<Image Source="pack://application:,,,/Skin;component/image/you.png" />
或者
<Image Source="/Skin;component/image/you.png" />
使用SiteOfOrigin
imgContent.Source = new BitmapImage(new Uri("pack://SiteOfOrigin:,,,/images/my.jpg"));