WPF中的StaticResource和DynamicResource有什么区别? [英] What's the difference between StaticResource and DynamicResource in WPF?

查看:36
本文介绍了WPF中的StaticResource和DynamicResource有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF中使用画笔、模板、样式等资源时,可以指定为StaticResources

When using resources such as brushes, templates and styles in WPF, they can be specified either as StaticResources

<Rectangle Fill="{StaticResource MyBrush}" />

或作为动态资源

<ItemsControl ItemTemplate="{DynamicResource MyItemTemplate}"  />

大多数时候(总是?),只有一个有效,另一个会在运行时抛出异常.但我想知道为什么:

Most of the times (always?), only one works and the other will throw exception during runtime. But I'd like to know why:

  • 主要区别是什么.像内存或性能影响
  • WPF 中是否有画笔始终是静态的"和模板始终是动态的"等规则?

假设静态与动态之间的选择并不像看起来那么随意......但我看不到模式.

I assume the choice between Static vs Dynamic isn't as arbitrary as it seems... but I fail to see the pattern.

推荐答案

A StaticResource 将在实际运行应用程序之前加载 XAML 期间解析并分配给属性.它只会被分配一次,并且忽略对资源字典的任何更改.

A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.

A DynamicResource 分配在加载期间为属性添加一个 Expression 对象,但直到运行时当 Expression 对象被要求提供值时才实际查找资源.这会推迟查找资源,直到在运行时需要它.一个很好的例子是对稍后在 XAML 中定义的资源的前向引用.另一个例子是直到运行时才会存在的资源.如果源资源字典发生变化,它将更新目标.

A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.

这篇关于WPF中的StaticResource和DynamicResource有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆