名为IsGrayProperty 的静态只读DependencyProperty 是一个标识符——可以说是一个键值。它还包含有关该属性的元数据。它不是实际财产本身。每个DependencyObject 实例在内部存储自己的DependencyProperty 值。
依赖属性在语义上与常规实例属性非常相似,但它们具有额外的功能,可以让它们做常规实例属性不能做的事情(例如,您可以在运行时更改它们的元数据,与常规属性上的Attributes 不同,您可以创建附加属性)。这就是它们存在的原因。
例如,TextBlock.Text 是一个依赖属性。
//
// Summary:
// Identifies the System.Windows.Controls.TextBlock.Text dependency property.
//
// Returns:
// The identifier of the System.Windows.Controls.TextBlock.Text dependency property.
[CommonDependencyProperty]
public static readonly DependencyProperty TextProperty;
它也有一个“常规属性”包装器:
//
// Summary:
// Gets or sets the text contents of a System.Windows.Controls.TextBlock.
//
// Returns:
// The text contents of this System.Windows.Controls.TextBlock. Note that all
// non-text content is stripped out, resulting in a plain text representation
// of the System.Windows.Controls.TextBlock contents. The default is System.String.Empty.
[Localizability(LocalizationCategory.Text)]
public string Text { get; set; }
当您设置一个TextBlock 的Text 时,其他所有TextBlock 是否共享相同的文本?不,当然不。如果他们这样做了,依赖属性将完全没用。
GetValue 的DependencyProperty 参数告诉DependencyObject 从依赖对象自己的内部属性值存储中检索哪个值;如果该值存储在DependencyProperty 本身中,您将查询DependencyProperty,不是DependencyObject。
public void ForExample(TextBlock tb)
{
var oldtext = tb.GetValue(TextBlock.TextProperty) as String;
tb.SetValue(TextBlock.TextProperty, "Test value");
}
如果TextBlock.TextProperty 只有一个全局值,并且它存储在TextBlock.TextProperty,那么我们到底为什么要在@987654344 的某个随机实例上调用GetValue() 和SetValue() @?为什么要让一个特定的TextBlock 实例参与其中?
相反,我们会调用TextBlock.TextProperty.SetValue()。
这就像一个字典:
var d1 = new Dictionary<String, Object>();
var d2 = new Dictionary<String, Object>();
var keyValue = "Foo";
d1.Add(keyValue, 32);
Console.WriteLine( d2[keyValue] );
您对d2[keyValue] 有什么期望?你会期望什么都没有,因为你从来没有给d2 一个keyValue 的值。 d1.Add("Foo",32) 不将整数 32 存储在字符串 "Foo" 中。它将它存储在字典中。
每个字典都存储自己的键值。每个DependencyObject 都存储自己的属性值。在内部,它可能将它们存储在 in Dictionary;为什么不?如果 .NET 团队可以编写比Dictionary 更有效的存储键/值对的方法,他们会称之为Dictionary。
当您对语言或框架功能的含义有所了解时,请始终问自己:“如果我的想法是正确的,那么该功能会完全无用还是会带来巨大的危害?”如果该问题的答案是“是”,那么您对该功能的含义猜错了。这是 100% 保证的,因为语言和框架的设计者和实现者不会习惯性地浪费几个月的时间来设计完全无用的功能 (classes in Perl 5 come close, though)。