首页 / 软件开发 / Silverlight / WPF and Silverlight学习笔记(十六):WPF资源(Resource)(1)
WPF and Silverlight学习笔记(十六):WPF资源(Resource)(1)2010-12-17 博客园 龙腾于海一、什么是资源通常使用 WPF 资源作为重用通常定义的对象和值的 简单方法。例如定义一种可以复用的单色的Brush对象,按钮的背景及矩形的填 充颜色均使用此Brush:1: <Window x:Class="WPFResource.WinBasicResource"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation& quot;
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: Title="Basic Resource" Height="200" Width="300">
5: <Window.Resources>
6: <SolidColorBrush x:Key="myBrush" Color="Gold" />
7: </Window.Resources>
8: <StackPanel>
9: <Button Margin="5" Content="Sample Button" Background="{StaticResource myBrush}" />
10: <Rectangle Margin="5" Width="100" Height="100" Fill=" {StaticResource myBrush}" />
11: </StackPanel>
12: </Window>
在WPF中资源 通常用作“样式”(Style)、样式模板、数据模板等。二、 资源的定义及XAML中引用资源可以定义在以下几个位置:应用程 序级资源:定义在App.xaml文件中,作为整个应用程序共享的资源存在在App.xaml文件中定义:1: <Application x:Class="WPFResource.App"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation& quot;
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: StartupUri="Window1.xaml">
5: <Application.Resources>
6: <SolidColorBrush Color="Gold" x:Key="myGoldBrush" />
7: </Application.Resources>
8: </Application>
在ApplicationResourceDemo.xaml文件( 窗体)中使用App.xaml中定义的Resource1: <Window x:Class="WPFResource.ApplicationResourceDemo"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation& quot;
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: Title="Application Resource Demo" Height="300" Width="300">
5: <StackPanel>
6: <Button Margin="5" Background="{StaticResource myGoldBrush}">Sample Button</Button>
7: </StackPanel>
8: </Window>
窗体级资源:定义在Window或Page中,作为一 个窗体或页面共享的资源存在1: <Window x:Class="WPFResource.WindowResourceDemo"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation& quot;
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: Title="WindowResourceDemo" Height="300" Width="300">
5: <Window.Resources>
6: <SolidColorBrush x:Key="myRedBrush" Color="Red" />
7: </Window.Resources>
8: <StackPanel>
9: <Button Margin="5" Background="{StaticResource myRedBrush} ">Sample Button</Button>
10: </StackPanel>
11: </Window>