避免讓WPF資源字典變得雜亂臃腫

2021-04-17 09:31:57 字數 2897 閱讀 8704

避免讓wpf資源字典變得雜亂臃腫

周銀輝

今天看到專案種的乙個***resource.xaml檔案

**有二千多行,這引發了我一些思考:如何組織我們的wpf資源。在wpf中可以有很多種組織資源的方式,下面分別介紹:

1,每個元素維持自己的資源

<

buttonx:

name

="btn1"

content

="button 1"

foreground

="">

<

button.resources

>

<

solidcolorbrushx:

key="redbrush"

color

="red"/>

button.resources

>

button

>

<

buttonx:

name

="btn2"

content

="button 2"

foreground

="">

<

button.resources

>

<

solidcolorbrushx:

key="redbrush"

color

="red"/>

button.resources

>

button

>

這造成的問題是,資源不能共享而重複建立一些相同的資源影響效率。

2,提高資源共享率。我們可以將共享的資源轉移更高的層次中,以便底層次的元素可以直接引用這些資源,而不必各自重新建立,比如:

<

stackpanel

>

<

stackpanel.resources

>

<

solidcolorbrushx:

key="redbrush"

color

="red"/>

stackpanel.resources

>

<

buttonx:

name

="btn1"

content

="button 1"

foreground

="">

button

>

<

buttonx:

name

="btn2"

content

="button 2"

foreground

="">

button

>

stackpanel

>

我們將redbrush

移動到了兩個

button

的公共父親

stackpanel

中,這樣他們就可以同時引用了。

但通常情況下,為了更大範圍的共享,我們會將很多

resoureces

移動到window

(或page

)甚至範圍內。

但隨著資源的增多,如果我們將這些資源都塞進乙個

xaml

檔案中,那麼我們的

xaml

檔案將變得非常的臃腫(

比如一不小心就幾千行,其閱讀性將變得很差,並且要想快速導航到欲查詢的資源也不容易)。為此,我們得考慮如何重新組織我們的資源來解決這個問題。

一種可行的方式是將

resource

按照型別來劃分到不同的

resourcedictionary

檔案中,然後使用

mergeddictionaries

來合併各個資源字典。在進行分組之前所有的資源都在同乙個資源字典中,如下圖:

我們按照不同的型別分組後(

brushes

,datatemplates

,styles

,converters等等,

每一種型別對應乙個資源字典,這樣資源字典就被拆分得比較小了),如下圖:

然後在將這些字典合併成乙個字典來使用:

<

>

<

resourcedictionary

>

<

resourcedictionary.mergeddictionaries

>

<

resourcedictionary

source

="resources"brushes.xaml"/>

<

resourcedictionary

source

="resources"styles.xaml"/>

<

resourcedictionary

source

="resources"datatemplates.xaml"/>

resourcedictionary.mergeddictionaries

>

resourcedictionary

>

>

這樣乙個明顯的好處是,讓我們資源組織得更加的結構化,更好的查詢和維護,更適合程式設計師的觀點。但其明顯的乙個缺點是

blend

的resource

目錄面板對您多建立的資源的多級目錄結構表現得不明顯,不能展現目標的多層結構而展現成乙個平面結構,導致你不在區分不同資料夾下的同名資源檔案時又些不方便(但,你可以把滑鼠移動到檔案上,其

tooltip

會顯示各自的完整路徑來區分),如下圖:

WPF 資源字典

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

WPF合併資源字典

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

WPF 合併資源字典

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