【发布时间】:2014-12-31 08:38:00
【问题描述】:
来自google,很多文章说DependencyProperty是静态的,因为它有一个KeyValue机制来维护对象每个实例的值。
但问题是,如果我们针对 DependencyProperty 调用 GetValue / SetValue,它如何识别每个实例并生成密钥以便从 HashTable 中读取/保存对象的不同实例的值?
例如:如果我们创建2个TestDp实例,然后为两个实例的TestDProperty设置值,SetValue如何识别每个实例并将DependencyProperty值相应地保存到哈希表中?
我检查了 DependencyObject 的 GetValue 和 SetValue 的代码,但我仍然无法弄清楚它是如何区分每个实例的。代码 this.LookupEntry(dp.GlobalIndex) 将获取 EntryIndex,但我不确定如何生成 GlobalIndex 以区分对象的每个实例。
public class TestDp : DependencyObject
{
protected static DependencyProperty dpTest = DependencyProperty.Register("TestDProperty", typeof(string), typeof(TestDp));
public string TestDProperty
{
get
{
var r = (string)GetValue(dpTest);
return r;
}
set
{
SetValue(dpTest, value);
}
}
}
【问题讨论】:
-
不确定我是否理解您的问题,但您在
DependencyObject的当前实例上致电GetValue/SetValue。此外,dpTest应命名为TestDProperty,CLR 包装器应命名为TestD和注册属性的名称 "TestD" -
为两个实例的 TestDProperty 设置值 当你这样做时,你当然必须在 SetValue >不同的实例,因此它知道将数据分别保存在哪里。请注意,数据仅在具有默认值时才共享,一旦针对某些特定实例更改,将不再共享。
-
我检查了 DependencyObject 的 GetValue 和 SetValue 的代码,但我仍然无法弄清楚它是如何区分每个实例的。代码 this.LookupEntry(dp.GlobalIndex) 将获取 EntryIndex 但我不确定如何生成 GlobalIndex 以区分对象的每个实例。
-
@mind1n
DependencyProperty定义是静态的,但this.GetValue(...)和this.SetValue(...)是DependencyObject的实例方法,因此将在当前实例上调用this.LookupEntry(...)
标签: wpf dependency-properties dependencyobject