#167 – Implementing a Dependency Property That Is A Collection

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
About these ads

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

3 Responses to #167 – Implementing a Dependency Property That Is A Collection

  1. 3J says:

    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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 378 other followers

%d bloggers like this: