您的位置:首页 > 其它

动态资源DynamicResource与静态资源StaticResource的区别

2016-03-07 14:34 176 查看
静态资源在第一次编译后即确定其对象或值,之后不能对其进行修改。动态资源则是在运行时决定,当运行过程中真正需要时,才到资源目标中查找其值。引用动态资源时,当被引用的动态资源发生变化时,引用这个资源的相应属性会自动跟着变化。

先看看这段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运行时才查找并加载所定义的资源。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: