#167 – Implementing a Dependency Property That Is A Collection
December 26, 2010 3 Comments
When you create a custom dependency property that is based on a collection type, you need to define the default value of the property as a new instance of a collection, rather than as just a static value.
For example, we defined the Person.IQ dependency property, with a default value of 100, as follows:
internal static readonly DependencyPropertyKey IQPropertyKey = DependencyProperty.RegisterReadOnly("IQ", typeof(int), typeof(Person), new PropertyMetadata(100));
If we define a read-only Person.Friends property, whose type is List<Person>, the same call would look like this:
internal static readonly DependencyPropertyKey FriendsPropertyKey = DependencyProperty.RegisterReadOnly("Friends", typeof(List<Person>), typeof(Person), new PropertyMetadata(new List<Person>())); // Metadata constructor instantiates a new List
This is not correct. The default value will be shared by all instances of the dependency object. Therefore, the default value should be set outside of the class’s static constructor.
The intent WAS to share the default value across all instances.
From my understanding, this is not correct for the collection. You are sharing the reference of the list not a new List instance. As a consequence all the items that are using this DP will shared the same collection.
ref: http://msdn.microsoft.com/en-us/library/aa970563(v=vs.100).aspx#initializing