本文讨论StaticResource和DynamicResource众多区别中的一项——关于修改资源的问题。关于向前引用什么的问题,请参考Google。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow">
<Window.Resources>
<SolidColorBrush x:Key="sr" Color="Gold" />
<SolidColorBrush x:Key="dr" Color="Gold" />
</Window.Resources>
<DockPanel>
<StackPanel DockPanel.Dock="Top">
<TextBlock Text="StaticResource sr" Background="{StaticResource sr}" />
<TextBlock Text="DynamicResource dr" Background="{DynamicResource dr}" />
<TextBlock Text="DynamicResource a" Background="{DynamicResource a}" />
</StackPanel>
<StackPanel Name="grid" Orientation="Horizontal">
<StackPanel.Resources>
<Style TargetType="Button">
<Style.Setters>
<Setter Property="Margin" Value="5"/>
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="60"/>
</Style.Setters>
</Style>
</StackPanel.Resources>
<Button Content="改资源的属性" Click="button1_Click" />
<Button Content="改资源本身" Click="Button2_Click" />
<Button Content="创建资源a" Click="Button3_Click" />
</StackPanel>
</DockPanel>
</Window>
private void button1_Click(object sender, RoutedEventArgs e)
{
var sr = ((SolidColorBrush)FindResource("sr"));
System.Diagnostics.Debug.WriteLine(sr.IsFrozen);
sr.Color=Colors.Red;
var dr = ((SolidColorBrush)FindResource("dr"));
System.Diagnostics.Debug.WriteLine(dr.IsFrozen);
dr.Color = Colors.LightBlue;
}
private void Button2_Click(object sender, RoutedEventArgs e)
{
Resources["sr"] = new SolidColorBrush(Colors.SaddleBrown);
Resources["dr"] = new SolidColorBrush(Colors.AliceBlue);
}
private void Button3_Click(object sender, RoutedEventArgs e)
{
Resources["a"] = new SolidColorBrush(Colors.BurlyWood);
}
点击三个按钮查看效果。
可以发现
点击按钮1,1、2两个TextBlock背景颜色都改变。
点击按钮2,只有第二个TextBlock背景颜色改变。
点击按钮3,第三个TextBlock获得背景颜色。
所以,不论用StaticResource还是DynamicResource,修改资源的属性时,修改都会反映在使用此资源的元素上。如果修改资源本身,修改只会反映在用DynamicResource引用此资源的元素上。
另外需要注意的是,根据调试输出,这些资源都没有冻结!
可以这么冻结它:
xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"
PresentationOptions:Freeze="true"