WPF资源
什么是资源
通常使用WPF资源作为重用通常定义的对象和值的简单方法。例如定义一种可以复用的单色的Brush对象,按钮的背景及矩形的填充颜色均使用此Brush
在WPF中资源通常用作“样式”(Style)、样式模板、数据模板等。
<Window x:Class="WPFResource.WinBasicResource" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Basic Resource" Height="200" Width="300"> <Window.Resources> <SolidColorBrush x:Key="myBrush" Color="Gold" /> </Window.Resources> <StackPanel> <Button Margin="5" Content="Sample Button" Background="{StaticResource myBrush}" /> <Rectangle Margin="5" Width="100" Height="100" Fill="{StaticResource myBrush}" /> </StackPanel></Window>资源的定义及XAML中引用
定义位置
- 应用程序级资源:定义在App.xaml文件中,作为整个应用程序共享的资源存在
<Application x:Class="WPFResource.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="Window1.xaml"> <Application.Resources> <SolidColorBrush Color="Gold" x:Key="myGoldBrush" /> </Application.Resources></Application>- 窗体级资源:定义在Window或Page中,作为一个窗体或页面共享的资源存在
<Window x:Class="WPFResource.WindowResourceDemo" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WindowResourceDemo" Height="300" Width="300"> <Window.Resources> <SolidColorBrush x:Key="myRedBrush" Color="Red" /> </Window.Resources> <StackPanel> <Button Margin="5" Background="{StaticResource myRedBrush}">Sample Button </Button> </StackPanel></Window>- 文件级资源:定义在资源字典的XAML文件中,再引用
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <SolidColorBrush x:Key="myWhiteBrush" Color="White" /></ResourceDictionary>- 对象(控件)级资源:定义在某个ContentControl中,作为其子容器、子控件共享的资源
XAML解析资源的顺序
在XAML中解析资源按照由引用资源的控件向外层容器依次调用资源。例如在在应用程序级别、窗体级别及对象级别分为定义x:Key相的同资源:
对象级>窗体级>应用程序级
静态资源(StaticResource)和动态资源(DynamicResource)
资源可以作为静态资源或动态资源进行引用。这是通过使用 StaticResource 标记扩展或 DynamicResource 标记扩展完成的。
通常来说,不需要在运行时更改的资源使用静态资源;而需要在运行时更改的资源使用动态资源。动态资源需要使用的系统开销大于静态资源的系统开销。
静态资源引用是从控件所在的容器开始依次向上查找的,而动态资源的引用是从控件开始向上查找的(即控件的资源覆盖其父容器的同名资源)
更改资源时,动态引用的控件样式发生变化
不同类型的资源
- 程序集资源:这种常见于将图片设定到程序集中,做为程序集的资源
- 对象资源:统对于对象资源使用ResouceDictionary这个字典集合处理,其Key对应即x:Key声明的键,Value对应资源