最近學習一些了關於程序集之間共享資源的知識,在這裏記錄下來。
(1)創建
首先是共享資源的創建,創建一個新的“wpf自定義控件”項目,然後隨便添加一個圖片作爲示例資源。
文件結構如下:
資源字典文件(background.xaml)裏面的代碼如下:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Resource">
<ImageBrush x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:CustomControl1},ResourceId=test}" ImageSource="pack://application:,,,/Resource;component/Lighthouse.jpg"></ImageBrush>
</ResourceDictionary>
因爲這個資源是要作爲共享資源的,所以這裏要使用絕對 pack URI路徑
(2)資源配置
1.資源合併
如果你創建了多個資源字典作爲共享資源的話,進行資源合併就是必須的,資源合併的代碼寫在Generic.xaml裏:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Resource">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Resource;component/background.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
這裏的重點也和上面一樣,要使用絕對url路徑
2.類文件
這一步其實可以是可選的,但加上之後可以簡化資源的使用,因此也是用必要的
public class CustomControl1
{
public static ComponentResourceKey test
{
get
{
return new ComponentResourceKey(typeof(CustomControl1), "test");
}
}
}
(3)資源使用
資源準備好之後就可以使用了
1.命名空間包含
使用之前要先包含命名空間:
xmlns:res="clr-namespace:Resource;assembly=Resource"
2.使用
直接在控件裏使用:
<Button MinHeight="100" Background="{DynamicResource {x:Static res:CustomControl1.test}}"></Button>
注意事項:
有時編譯器可能會報錯,可以先生成一次解決方案,如果錯誤消失就不用管它了