Why dependency properties in WPF has to be Static

点点圈 提交于 2019-11-30 00:22:23

The magic here is, the declaration of DependencyProperty is static not its value (i.e the memory storage). The declaration that you add with static keyword is just the identifier(key) of the DependencyProperty for a particular DependencyObject. As same identifier/key can be used by all instances of the DependencyObject to identify the property value hence it makes sense to make it static.

On the other hand, when we set the value of DependancyProperty by calling the SetValue on DependancyObject instance, then each instance of DependancyObject on which the SetValue is called will store its local value of the Property. This is handled internally by the DependancyObject class which maintain sort of Dictionary which has the mapping between the DependancyProperty identifier and the local value.

DependencyProperty has to be static (Class level) because when we create multiple objects of the class which has that property and want to refer the default value for that property the value has to come from that static instance of DependencyProperty. So default value for all instance of our class is same and system does not reserve memory for DependencyProperty on each and every instance of that class. This way it reduces the memory footprint.

Now the next question arise what if we explicitly set the DependencyProperty’s value for objects of the class.(By code or by animation or by style)

In this case DependencyObject comes into the picture. Any class which has DependencyProperty has to be derived from DependencyObject class (WPF specific class which maintains a collection named EffectiveValues). When user set the DependencyProperty’s value explicitly on the object of the class(By code or by animation or by style), the value is stored in the that EffectiveValues collection which resides within the DependencyObject class and reserve memory there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!