在WPF應用程序開發中,總是難以記住各種訪問資源的方法,遂逐一記下。
先從資源是否編譯到程序集分類
一.程序集資源
資源在編譯的時候嵌入到程序集中。WPF中的XAML會被編譯為BAML,圖片等其他資源均被編譯到程序集中AssemblyResources.g.resources中
為了能夠成功使用程序集資源,需要注意一下兩點:
- 資源的Build Action必須是Resource,不復制到輸出目錄。
- 不要在Project Properties中使用Resource選項卡,WPF不支持這種類型的資源URI。
使用資源
可以在XAML中使用如下方式使用資源
<Image Source="Image/yun.png"></Image>
也可以使用代碼,不過這里有相對路徑和絕對路徑之分
img.Source=new BitmapImage(new Uri(@"E:\Photo\Image\yun.png")); img.Source=new BitmapImage(new Uri("Image/yun.png",UriKind.Relative));
但在實際項目中,資源總在另外一個程序集中,那么就需要跨程序集訪問資源。語法如下:
pack://application:,,,/AssemblyName;Component/ResourceName
首先要引用具有資源的程序集
在XAML中如下使用
<Grid> <Grid.Background> <ImageBrush ImageSource="pack://application:,,,/Controls;Component/Image/yun.png"></ImageBrush> </Grid.Background> </Grid>
在代碼中也是同樣的使用方式
img.Source=new BitmapImage(new Uri("pack://application:,,,/Controls;Component/Image/yun.png"));
另外就是資源字典的使用,一個資源字典中可以包含程序中需要使用的樣式,畫筆等等,資源文件也可再包含資源文件
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Dictionary.xaml"></ResourceDictionary> <ResourceDictionary Source="Dictionary2.xaml"></ResourceDictionary> </ResourceDictionary.MergedDictionaries> <Style x:Key="btnStyle" TargetType="Button"> <Setter Property="Background"> <Setter.Value> <ImageBrush ImageSource="Image/yun.png"></ImageBrush> </Setter.Value> </Setter> </Style> </ResourceDictionary>
如果程序需要使用到換膚功能的話,那么最好由Application來加載統一的資源字典,這樣實現換膚功能的話,其實就是將Application下的這一套資源換成另一套,唯一的弊端就是,在vs中看不到已經使用的樣式,只有運行起來才能看到。控件換膚也是同樣的道理。可以看下下面的例子
http://files.cnblogs.com/action98/WPF_ChangeSkin_Sample.rar
http://files.cnblogs.com/action98/CustomControl%E6%8E%A7%E4%BB%B6%E6%8D%A2%E8%82%A4.rar
二.內容文件
在如下情況中不宜使用程序集資源,而是使用應用程序部署文件。
- 希望改變資源文件,而又不想重新編譯應用程序。
- 資源文件非常大。
- 資源文件是可選的,並且可以不隨程序集一起部署。
- 資源是聲音文件。
為了能夠成功使用內容文件,需要注意兩點
- 將資源的Build Action始終設置為Content
- 將資源的Copy to Output Directory始終設置為CopyAlways
使用的時候同程序集使用的是同一套URI方法
Added by HeavenTao,2013/12/18