tags:

views:

256

answers:

3

Learning WPF nowadays. Found something new today with .Net dependency properties. What they bring to the table is

  • Support for Callbacks (Validation, Change, etc)
  • Property inheritance
  • Attached properties

among others.

But my question here is why do they need to be declared as static in the containing class? The recommmended way is to then add instance 'wrapper' property for them. Why ?

edit: @Matt, but doesn't that also mandate that the property value is also shared across instances - unless of course it is a derived value ?

+2  A: 

I see 2 reasons behind that requirement:

  1. You can't register same DP twice. To comply with this constraint you should use static variable, it will be initialized only one time thus you will register DP one time only.
  2. DP should be registered before any class (which uses that DB) instance created
aku
+4  A: 

I think the reason you need the static instance of a dependency property is really just because that's how they were designed. The static bit holds all the property metadata - its default value, its owner type (handy if it's an attached property) etc, its callback methods for when it changes - that sort of thing. Makes sense to store these things statically across all instances of the class rather than per-instance.

Matt Hamilton
+7  A: 

Dependency properties are static because of a key optimization in WPF: Many of the controls in WPF have tens, if not hundreds of properties. Most of the properties in these classes are set to their default value. If DP's where instance properties, memory would need to be allocated for every property in every object you create. Since DP's are static, WPF is free to manage each properties memory usage more effectively.

The reason why you should supply a default value for any DP you register is because WPF will take care not to allocate extra memory for you property when it's set to its default value, no matter how many objects containing that property you create.

Anthony Conyers