WPF and Silverlight学习笔记(十七):WPF资源(Resource)(2)2010-12-17 博客园 龙腾于海四、静态资源(StaticResource)和动态资源(DynamicResource)资源可以作为静态资源或动态资源进行引用。这是通过使用 StaticResource 标 记扩展或 DynamicResource 标记扩展完成的。通常来说,不需要在运行 时更改的资源使用静态资源;而需要在运行时更改的资源使用动态资源。动态资 源需要使用的系统开销大于静态资源的系统开销。例如以下的例子:
1: <Window  x:Class="WPFResource.StaticAndDynamicResource"
2:    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation& quot;
3:    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4:   Title="StaticAndDynamicResource"  Height="200" Width="300">
5:    <Window.Resources>
6:     <SolidColorBrush  x:Key="ButtonBrush" Color="Red" />
7:    </Window.Resources>
8:   
9:    <StackPanel>
10:     <Button Margin="5"  Content="Static Resource Button A" Background=" {StaticResource ButtonBrush}" />
11:      <Button Margin="5" Content="Static Resource  Button B" Background="{StaticResource ButtonBrush} ">
12:       <Button.Resources>
13:          <SolidColorBrush x:Key="ButtonBrush"  Color="Yellow" />
14:        </Button.Resources>
15:     </Button>
16:      <Button Margin="5" Content="Change Button  Resource" Click="Button_Click" />
17:      <Button Margin="5" Content="Dynamic Resource  Button A" Background="{DynamicResource ButtonBrush} " />
18:     <Button Margin="5"  Content="Dynamic Resource Button B" Background=" {DynamicResource ButtonBrush}">
19:        <Button.Resources>
20:         <SolidColorBrush  x:Key="ButtonBrush" Color="Yellow" />
21:       </Button.Resources>
22:      </Button>
23:   </StackPanel>
24:  </Window>
1: private void Button_Click(object  sender, RoutedEventArgs e)
2: {
3:   SolidColorBrush  brush = new SolidColorBrush(Colors.Green);
4:    this.Resources["ButtonBrush"] = brush;
5: } 以上的例子在运行时显示如下:

而点击“Change Button Resource”按钮后,显示的结果 为:
