Why a dependency property has to be Static?
I have seen that it has been already asked in some post here, but I am not able to understand it properly.
It will be great if someone can help me understand with a small snippet too.
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.
来源:https://stackoverflow.com/questions/19441453/why-dependency-properties-in-wpf-has-to-be-static