“Logical resources may be of various types, such as brushes, geometries, styles, and templates.
Placing all those resources in a single file such as App.xaml hinders maintainability. A better
approach would be to separate resources of different types (or based on some other criteria) to
their own files. Still, they must be referenced somehow from within a common file such as App.
xaml so they are recognized.”app
为了增长资源文件的可维护性,咱们应该使用ResourceDictionary对资源进行:分类、汇总。spa
如何实现呢?举个例子3d
1.新建一个WPF Application,在Application中添加一个New Item,选择ResourceDictionary。code
譬如,命名为Brushes.xaml,咱们用它来存放一些笔刷。打开,咱们添加一个笔刷以下:xml
Brushes.xaml:blog
<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。
“Open App.xaml. We need to merge external resource dictionaries into the main
application dictionary.”ip
打开App.xaml,添加以下内容:ci
<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>
效果同上,以下: