1. 程式人生 > 其它 >WPF中的嵌入的資源與Resource

WPF中的嵌入的資源與Resource

技術標籤:WPF面向物件程式設計C#c#嵌入的資源Resource

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"));

參考連結:
https://www.cnblogs.com/sntetwt/p/5402098.html