Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do .Net WPF DependencyProperties have to be static members of the class

Tags:

.net

wpf

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 ?

like image 960
Gishu Avatar asked Dec 10 '22 23:12

Gishu


1 Answers

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 were 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 property's 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 your property when it's set to its default value, no matter how many objects containing that property you create.

like image 99
Anthony Conyers Avatar answered May 18 '23 13:05

Anthony Conyers