WPF DependencyProperty如何选取键来区分对象的每个实例并查找DependencyProperty的值?
谷歌的很多文章都说DependencyProperty是静态的,因为它有一个KeyValue机制来维护对象每个实例的值WPF DependencyProperty如何选取键来区分对象的每个实例并查找DependencyProperty的值?,wpf,dependency-properties,dependencyobject,Wpf,Dependency Properties,Dependencyobject,谷歌的很多文章都说DependencyProperty是静态的,因为它有一个KeyValue机制来维护对象每个实例的值 public class TestDp : DependencyObject { protected static DependencyProperty dpTest = DependencyProperty.Register("TestDProperty", typeof(string), typeof(TestDp)); publi
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);
}
}
}
但问题是,如果我们针对DependencyProperty调用GetValue/SetValue,它如何识别每个实例并生成键,以便从哈希表中读取/保存对象不同实例的值
例如:如果我们创建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将调用GetValueEntry并使用您提到的EntryIndex。但是,它似乎不会根据实例信息生成任何密钥。我不确定是否理解您的问题,但您可以在
DependencyObject
的当前实例上调用GetValue
/SetValue
。此外,dpTest
应命名为TestDProperty
,CLR包装器应命名为TestD
,并且注册属性的名称“TestD”为两个实例的TestDProperty设置了值。执行此操作时,您当然必须在不同的实例上调用SetValue
,以便它知道在何处分别保存数据。请注意,数据只有在具有默认值时才会共享,一旦它们为某个特定实例更改,它们将不再共享。我已经检查了DependencyObject的GetValue和SetValue代码,但我仍然无法确定它如何区分每个实例。代码this.LookupEntry(dp.GlobalIndex)将拾取EntryIndex,但我不确定如何生成GlobalIndex来区分对象的每个实例。@mind1ndependencProperty
定义是静态的,但this.GetValue(…)
和this.SetValue(…)
是DependencyObject
的实例方法,因此将在当前实例上调用,就像this.LookupEntry(…)
一样。右侧,在注册属性时生成的每个DP只有一个全局索引。这就是“钥匙”。没有特定于实例的密钥。