为什么 WPF 中的依赖属性必须是静态的 [英] Why dependency properties in WPF has to be Static
问题描述
为什么依赖属性必须是静态的?
Why a dependency property has to be Static?
我已经看到这里的一些帖子已经问过了,但我无法正确理解它.
I have seen that it has been already asked in some post here, but I am not able to understand it properly.
如果有人也能用一小段代码帮助我理解就好了.
It will be great if someone can help me understand with a small snippet too.
推荐答案
这里的神奇之处在于,DependencyProperty
的声明是 static
而不是它的 value代码>(即内存存储).您使用
static
关键字添加的声明只是特定DependencyObject
的DependencyProperty
的标识符(键).由于 DependencyObject 的所有实例都可以使用相同的标识符/键来标识属性值,因此将其设置为 static
是有意义的.
The magic here is, the declaration of DependencyProperty
is static
not its value
(i.e the memory storage). The declaration that you add with static
keyword is just the identifier(key) of the DependencyProperty
for a particular DependencyObject
. As same identifier/key can be used by all instances of the DependencyObject to identify the property value hence it makes sense to make it static
.
另一方面,当我们通过在 DependancyObject
实例上调用 SetValue
来设置 DependancyProperty
的值时,那么 的每个实例调用 SetValue 的 >DependancyObject
将存储其本地属性值.这是由 DependancyObject
类在内部处理的,该类维护一种 Dictionary
,它具有 DependancyProperty
标识符和本地值之间的映射.
On the other hand, when we set the value of DependancyProperty
by calling the SetValue
on DependancyObject
instance, then each instance of DependancyObject
on which the SetValue is called will store its local value of the Property. This is handled internally by the DependancyObject
class which maintain sort of Dictionary
which has the mapping between the DependancyProperty
identifier and the local value.
这篇关于为什么 WPF 中的依赖属性必须是静态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!