WPF加載程序集中字符串資源


 

WPF資源

WPF資源使用其實的也是resources格式嵌入資源,默認的資源名稱為"應用程序名.g.resources",不過WPF資源使用的pack URI來訪問資源。

添加圖像資源 

在解決方案資源管理器中包含一個圖像資源(如data\img.png)的時候,默認是輸出為資源文件的(生成操作=Resource),編譯的時候作為資源編譯到程序集中;

當在img.png的屬性頁中把"生成操作"屬性設置為"內容",同時設置"復制到輸出目錄"屬性為"如果較新則復制",則輸出為內容文件,data\img.png會復制一份到程序集輸出目錄,這樣無需編譯就可以修改資源文件了。

此圖片資源的uri鏈接為"/data/img.png",如<Image Name="image3" Source="/data/img.png" />

在資源字典中使用字符串

ResouceDictionary中可以添加各種類型資源,使用如下方法來保存字符串到資源字典中。資源字典默認情況下會被編譯成baml保存到"應用程序名.g.resources"資源中,也可以修改輸出為內容文件方法同上。

資源字典的xaml代碼:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <sys:String x:Key="rdstring1">resource dictionary string.</sys:String>
</ResourceDictionary>

 

別忘了在app.xaml中添加這個資源字典的引用:

<Application 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="MySampleApp1.app">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

 

xaml代碼中使用此字符串:

<Label Content="{StaticResource rdstring1}" Name="label8" />

 

代碼中使用此字符串:

string msg= (string)Application.Current.FindResource("rdstring1");
MessageBox.Show(msg);

 

 轉載:http://www.cnblogs.com/xwing/archive/2009/05/31/1493256.html

先准備一個WPF資源類庫:新建一個程序集,默認創建的東西都刪掉,添加上面的資源字典dictionary1.xaml到類庫中,編譯為ClassLibrary1.dll,使用Reflector工具檢查發現這個類庫中資源名為:ClassLibrary1.g.resources,內容為dictionary1.baml,ok准備完畢。 

主程序集中無需引用這個資源庫,只需要放在同一個輸出目錄下即可,在代碼中加載此資源並合並到Application中。 

加載代碼(相對URI): 

var uri = new Uri("/ClassLibrary1;component/Dictionary1.xaml", UriKind.Relative);
var res = (ResourceDictionary)Application.LoadComponent(uri);
Application.Current.Resources.MergedDictionaries.Add(res);

 

加載代碼(絕對URI): 

var uri = new Uri("pack://application:,,,/ClassLibrary1;component/Dictionary1.xaml");
ResourceDictionary res = new ResourceDictionary {Source = uri};
Application.Current.Resources.MergedDictionaries.Add(res);

 

在XAML中直接加載:

復制代碼
<Application 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="MySampleApp.app">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/ClassLibrary1;component/Dictionary1.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM