[英]Why registering two identical attached properties works in Silverlight but fails in WPF?
[英]WPF/Attached Properties - Please explain why this works
請幫助我了解值“ABC”的存儲位置。 當我運行 memory 分析器時,我看不到 MyClass 的任何實例,實際上綁定有效並且 GroupBox.Header 獲得值 ABC...
謝謝你的幫助。
<GroupBox Header="{Binding Path=(local:MyClass.Tag1), RelativeSource={RelativeSource Self}}"
local:MyClass.Tag1="ABC" />
public class MyClass
{
public static readonly DependencyProperty Tag1Property = DependencyProperty.RegisterAttached("Tag1", typeof(object), typeof(MyClass), new UIPropertyMetadata(null));
public static object GetTag1(DependencyObject obj)
{
return obj.GetValue(Tag1Property);
}
public static void SetTag1(DependencyObject obj, object value)
{
obj.SetValue(Tag1Property, value);
}
}
依賴屬性在內部維護一個字典。 使用稀疏存儲機制存儲值。 這些屬性在 class 級別關聯 - 即 static。 值 ABC 作為鍵值對存儲在字典中
這是對其工作原理的非常直接的解釋: http://nirajrules.wordpress.com/2009/01/19/inside-dependencyobject-dependencyproperty/
本質上,正如 Hasan Fahim 所說,依賴屬性存儲在基於屬性名稱和屬性所有者的內部 Hashtable 中。 通過將屬性存儲為與所有者相關聯,您實際上可以在 HashTable 中為相同類型的不同對象擁有唯一的整體。 這意味着 Get 和 Set 方法不需要是 static。
例子:
public class Something
{
public static readonly DependencyProperty IsEditableProperty = DependencyProperty.Register("IsEditable", typeof(Boolean), typeof(ResourceCanvas), new PropertyMetadata(true));
public Boolean IsEditable
{
get { return (Boolean)this.GetValue(IsEditableProperty); }
set { this.SetValue(IsEditableProperty, value); }
}
}
使用版本,我可以實例化許多類型為 Something 的實例,每個實例都包含 IsEditable 的“不同”值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.