引用地址:https://www.cnblogs.com/zhaowei303/articles/4265468.html
一、ResourceDictionary一般使用
为了增加资源文件的可维护性,我们应该使用ResourceDictionary对资源进行:分类、汇总。
如何实现呢?举个例子
1.新建一个WPF Application,在Application中添加一个New Item,选择ResourceDictionary。
譬如,命名为Brushes.xaml,我们用它来存放一些笔刷。打开,我们添加一个笔刷如下:
Brushes.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> LinearGradientBrush EndPoint="1,0" x:Key="brush1"> <GradientStop Color="Violet" Offset="0" /> <GradientStop Color="Orange" Offset=".7" /> <GradientStop Color="Brown" Offset="1" /> </LinearGradientBrush> </ResourceDictionary>
2.在App.xaml中Merge则个Resource。
<Application x:Class="ManagingLogicalResources.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="Brushes.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application>
3.这样我们就可以在页面中正常使用了。
<Window x:Class="ManagingLogicalResources.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"> <Grid> Ellipse Fill="{StaticResource brush1}"/> </Grid> </Window>
-----------------------------------
在实际开发中更常用的做法是:直接在使用的View内部Merge。
<Window x:Class="WPFMergedDicitonary.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"> Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Brushes.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources> <Grid> <Ellipse Fill="{StaticResource brush1}"/> </Grid> </Window>
二、WPF工程中,用Blend工具自定义了许多ResourceDictionary,在各个工程中公用的方法:
1. 创建一个新的工程,然后把ResourceDictionary文件加入到改工程中。
2. 使用改ResourceDictionary的工程添加共享工程的reference,并在使用的窗口中合并dictionary,合并代码如下:
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml"/>
<ResourceDictionary.MergedDictionaries/>
<ResourceDictioAnary/>
3. 然后就像使用本地工程样使用style,template等公用的资源。