Proper pattern for defining collection type Dependency Properties?

I’ll relate a query that I recently posted on the Silverlight forums here, in case someone reading this has a good answer:

So, we all know that when creating a Dependency Property that has a collection type that setting a new collection instance as the default value in the metadata does not have the desired effect as that instance will be shared between all instances of the class as the default value of that property. So the correct solution is to initialize the collection instance in the constructor, see http://msdn.microsoft.com/en-us/library/cc903961(VS.95).aspx

But what if you want to set a value for this collection via a style? Or set its default value in the default style? For an example, see the Palette property on the Silverlight Toolkit chart. If we provide a value locally in the constructor, this will take precedence over the value provided in the style correct? Or if we avoid initializing the collection in the constructor, as in the Palette example, then this will not work:

<CustomControl.CollectionProperty>
   <CollectionItem />
   <CollectionItem />
</CustomControl.CollectionProperty>

only this will:

<CustomControl.CollectionProperty>
   <CollectionItemCollection>
       <CollectionItem />
       <CollectionItem />
   </CollectionItemCollection>
</CustomControl.CollectionProperty>

So, if you need a collection property to be stylable you can avoid setting it in the constructor and document that when used in xaml it needs a new collection instance to be instantiated. But what happens when tools like blend blithely create the former xml snippet when you use their collection editor?

Does anyone know a good pattern that allows for all these behaviors?

Advertisements

One Response to Proper pattern for defining collection type Dependency Properties?

  1. […] 27, 2010 In my last post on this subject, I was trying to track down a good way to avoid setting the default for a […]

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

%d bloggers like this: