WPF資源字典使用

2022-02-27 02:15:23 字數 2753 閱讀 3326

資源字典出現的初衷就在於可以實現多個專案之間的共享資源,資源字典只是乙個簡單的xaml文件,該文件除了儲存希望使用的資源之外,不做任何其它的事情。

1.建立資源字典

<

resourcedictionary

xmlns

=""xmlns:x

="">

<

style

x:key

="mybtnstyleone"

targettype

="button"

>

<

setter

property

="fontfamily"

value

="arial"

>

setter

>

<

setter

property

="padding"

value

="10"

>

setter

>

<

setter

property

="width"

value

="100"

>

setter

>

<

setter

property

="height"

value

="40"

>

setter

>

style

>

<

lineargradientbrush

x:key

="fadebrush"

>

<

gradientstop

color

="red"

offset

="0"

/>

<

gradientstop

color

="gray"

offset

="1"

/>

lineargradientbrush

>

resourcedictionary

>

說明:在建立資源的時候要確保資源檔案的編譯選項為page,這樣就能夠保證xaml資源檔案最終能夠編譯為baml檔案。但是如果設定為resource也是乙個不錯的選擇,這樣它能夠嵌入到程式集中,但是不被編譯,當然其解析的速度回稍微慢一點。

2.使用資源字典

2.1整合資源

<

x:class

xmlns

=""xmlns:x

=""startupuri

="mainwindow.xaml"

>

<

>

<

resourcedictionary

>

<

resourcedictionary.mergeddictionaries

>

<

resourcedictionary

source

="resource/mybuttonstyle.xaml"

/>

resourcedictionary.mergeddictionaries

>

resourcedictionary

>

>

>

說明:上面的標記通過明確地建立乙個resourcedictionary物件進行工作,資源集合總是resourcedictionary物件。但是這只是需要明確指定細節從而可以設定resourcedictionary.mergeddictionaries屬性的一種情況。如果沒有這個步驟resourcedictionary.mergeddictionaries屬性將為空。resourcedictionary.mergeddictionaries屬性是乙個resourcedictionary物件的集合,可以使用這個集合提供自己需要使用的資源的集合。也就是說如果需要某個資源,只需要將與該資源相關的xaml檔案。新增到這個屬性中即可。如上面新增test.xaml一樣。

2.2使用資源

整合之後就可以在當前的工程中使用這些資源了。使用方法如下:

<

button

content

="獲取繫結資料"

style=""

background=""

horizontalalignment

="left"

margin

="283,49,0,0"

verticalalignment

="top"

/>

使用資源的方法比較簡單只需要使用staticresource關鍵字去新增即可。

3.總結:

使用資源字典的主要原因有兩個:

a. 提供**功能。

b. 儲存需要被本地話的內容(錯誤訊息字串等,實現軟編碼)

使用過程也比較簡單,歸納起來主要有下面幾個步驟:

1. 建立資源字典檔案  》 2. 資源字典整合 》  3. 使用字典中的資源

WPF 資源字典

使用好處 儲存需要被本地話的內容 錯誤訊息字串等,實現軟編碼 減少重複的 重用樣式,實現多個專案之間的共享資源 修改乙個地方所有引用的地方都會被修改,方便統一風格 使用方法,歸納起來主要有下面幾個步驟 a.建立資源字典檔案,b.資源字典整合 c.使用字典中的資源 說明 在建立資源的時候要確保資源檔案...

WPF合併資源字典

1.合併多個外部資源字典成為本地字典 示例 page.resources resourcedictionary resourcedictionary.mergeddictionaries resourcedictionary source myresourcedictionary1.xaml res...

WPF 合併資源字典

原文 wpf 合併資源字典 1.合併多個外部資源字典成為本地字典 語言xaml 示例 描述 合併多個外部資源字典成為本地字典。當需要合併更多字典的時候只要在 resourcedictionary.mergeddictionaries 節中順序增加引用。特別提示 合併字典 mergeddictiona...