DynamicResource与StaticResource的区别

来源:互联网 发布:数据类型 js 编辑:程序博客网 时间:2024/04/30 15:41

静态资源在第一次编译后即确定其对象或值,之后不能对其进行修改。动态资源则是在运行时决定,当运行过程中真正需要时,才到资源目标中查找其值。引用动态资源时,当被引用的动态资源发生变化时,引用这个资源的相应属性会自动跟着变化。
先看看这段XAML代码:
// LinearGradientBrush.xaml
<Window x:Class="BrawDraw.Com.LinearGradientBrush.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="LinearGradientBrush" Height="300" Width="300">
    <Canvas Background="{DynamicResource innerLgbResource}">
        <Canvas.Resources>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1" x:Key="innerLgbResource">
                    <GradientStop Color="Yellow" Offset="0.0" />
                    <GradientStop Color="Orange" Offset="0.5" />
                    <GradientStop Color="Red" Offset="1" />
                </LinearGradientBrush>
        </Canvas.Resources>
    </Canvas>
</Window>
注意:innerLgbResource是基于Yellow, Orange, Red三种颜色的渐变。

注意XAML代码中的这句:<Canvas Background="{DynamicResource innerLgbResource}">,Canvas的背景使用了动态资源。
如果你将它改为<Canvas Background="{StaticResource innerLgbResource}">,将会收到错误提示:“StaticResource reference 'innerLgbResource' was not found.”
出现此问题的原因是:StaticResource 查询行为不支持向后引用,即不能引用在引用点之后才定义的资源。
而DynamicResource可以向后引用,即DynamicResource运行时才查找并加载所定义的资源。