3

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);
    }
}
H.B.
  • 166,899
  • 29
  • 327
  • 400
Gus Cavalcanti
  • 10,527
  • 23
  • 71
  • 104

2 Answers2

2

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

Hasan Fahim
  • 3,875
  • 1
  • 30
  • 51
2

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:

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); }
    }
 }

With version I can instantiate many instances of type Something each containing a "different" value of IsEditable.

JMcCarty
  • 759
  • 5
  • 17
  • 1
    Thank you JMcCarty. Although you answer was correct I had to grant the correct answer to Hasan, for being the first to answer. I up-voted yours though. Thanks for the link! – Gus Cavalcanti Jun 07 '11 at 20:21