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

查看:608
本文介绍了什么是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}" />

或作为DynamicResource

or as a DynamicResource

<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规则,如刷总是静态和模板总是动态等?

我认为静态VS动态之间的选择并不像它看起来那样随心所欲......但我看不到的格局。

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

推荐答案

一个的的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.

一个 DynamicResource 转让装载过程中的防爆pression对象的属性,但实际上并没有查找资源,直到运行时,防爆pression对象要求的值。这会延迟仰视资源,直到需要它在运行时。一个很好的例子将是一个向前引用在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天全站免登陆