WPF/附加属性 - 请解释为什么它有效
请帮助我理解值“ABC”的存储位置。当我运行内存分析器时,我没有看到任何 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);
}
}
Please help me understand where the value "ABC" gets stored. When I run memory profilers I don't see any instance of MyClass, and in fact the binding works and the GroupBox.Header gets the value ABC...
Thanks for your help.
<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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
依赖属性在内部维护一个字典。使用稀疏存储机制来存储值。这些属性在类级别关联 - 是静态的。值 ABC 以键值对的形式存储在字典中
Dependency properties maintain a dictionary internally. Values are stored using sparse storage mechanism. These properties are associated at the class level - being static. The value ABC is stored in the dictionary as key value pairs
这是对其工作原理的非常直接的解释: http:// nirajrules.wordpress.com/2009/01/19/inside-dependencyobject-dependencyproperty/
本质上正如 Hasan Fahim 所说,依赖属性被存储在基于属性名称和属性所有者的内部哈希表中。通过将属性存储为与所有者关联,您实际上可以在哈希表中为同一类型的不同对象拥有唯一的整体。这意味着 Get 和 Set 方法不需要是静态的。
示例:
使用版本,我可以实例化 Something 类型的许多实例,每个实例都包含 IsEditable 的“不同”值。
Here is a pretty straight forward explanation of how it works: http://nirajrules.wordpress.com/2009/01/19/inside-dependencyobject-dependencyproperty/
Essentially as Hasan Fahim said, the dependency properties are stored in an internal Hashtable based on the property name and the owner of the property. By storing the property as associated with the owner, you can actually have unique entires in the HashTable for different objects of the same type. This means that the Get and Set methods do not need to be static.
Example:
With version I can instantiate many instances of type Something each containing a "different" value of IsEditable.