如果我们希望在多个项目中共享资源,那么我们可以通过资源字典的方式来实现。
资源字典就是一个简单的xaml文档,这个文档就是专门用来存储共享资源的。
1、创建资源字典
我们首先新建一个WPF程序,右键项目属性,添加一个资源字典项,然后我们添加两个图像刷的资源。
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ImageBrush x:Key="TileBrush1" TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 30 30" Opacity="3"
ImageSource="file:///E:/1%20program/2Graduate%20Courses/lab/WPF/26.Resource%20Dictionary/Images/CUG.png"></ImageBrush>
<ImageBrush x:Key="TileBrush2" TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 30 30" Opacity="3"
ImageSource="file:///E:/1%20program/2Graduate%20Courses/lab/WPF/26.Resource%20Dictionary/Images/CUG彩色.png"></ImageBrush>
</ResourceDictionary>
这样这个资源字典就算创建好了。
2、使用资源字典
为了使用资源字典,我们需要把字典合并到应用程序的资源集合中。
我们在app的xaml文件中添加资源字典,将刚刚创建的字典加进来。
<Application x:Class="_26.Resource_Dictionary.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
然后我们在主窗口的xaml文件中新建两个按钮,分别使用资源字典里面的两个画刷资源。
<Window x:Class="_26.Resource_Dictionary.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel Margin="5">
<Button Content="使用资源1" Name="button1" Width="Auto" Margin="5" Padding="5" FontSize="15"
Background="{DynamicResource ResourceKey=TileBrush1}"/>
<Button Content="使用资源2" Name="button2" Width="Auto" Margin="5" Padding="5" FontSize="15"
Background="{DynamicResource ResourceKey=TileBrush2}"/>
</StackPanel>
</Window>
我们可以看到效果:
3、在程序集之间共享资源
如果我们希望在多个应用程序之间可以共享资源,我们可以利用代码实现。
首先我们新建一个新的WPF项目,作为资源项目,在资源项目中新建一个xaml,里面定义好资源。
然后在要使用资源的主项目中把这个资源项目添加进来,右键引用添加这个资源项目的引用,新建一个按钮3,用来调用资源项目中的资源,接着重写著项目的主窗口的加载函数。
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ResourceDictionary rd = new ResourceDictionary();
rd.Source = new Uri("26.ResourceLibrary;component/DictionaryLibrary.xaml", UriKind.Relative);
this.button3.Background = (Brush)rd["TileBrush1"];
}
然后就可以实现了:
还有一种不使用代码的方法, 我们使用ComponentResourceKey标记扩展属性,为资源创建一个键名,然后WPF就知道该资源适用于程序间的资源共享了。