在WPF中的StaticResource和DynamicResource这2个Markup Extension使用上很相似,但是在实现上其实很不相同。一个显著的区别当然就是如其名字所提示的那样:StaticResource静态地搜索指定的ResourceKey,如果该Resource发生变化,使用StaticResource处的值不会随之变化。而DynamicResource则会随之变化。
使用以下的XAML还可以观察到得到StaticResource和DynamicResource值的不同之处。先想想Button背景的颜色是什么,然后再验证一下。
其一:
<Grid>
<Grid.Resources>
<SolidColorBrushColor="Gold"x:Key="Testme"/>
</Grid.Resources>
<ButtonBackground="{StaticResource Testme}">
<Button.Resources>
<SolidColorBrushColor="Red"x:Key="Testme"/>
</Button.Resources>
</Button>
</Grid>
其二:
<Grid>
<Grid.Resources>
<SolidColorBrushColor="Gold"x:Key="Testme"/>
</Grid.Resources>
<ButtonBackground="{DynamicResource Testme}">
<Button.Resources>
<SolidColorBrushColor="Red"x:Key="Testme"/>
</Button.Resources>
</Button>
</Grid>
本文探讨了WPF中StaticResource与DynamicResource的区别。StaticResource在资源查找后不会随资源变化更新,而DynamicResource会动态更新。通过两个XAML示例演示了不同资源引用方式导致的背景颜色差异。
1302

被折叠的 条评论
为什么被折叠?



