开发者

Why Dependency property are declared as static readonly?

开发者 https://www.devze.com 2023-02-23 15:09 出处:网络
It is clear to me why 开发者_JS百科dependency property are static and the question still remain on my mind is why we need to use Readonly keyword at the time of declaration of Dependency Property.Conc

It is clear to me why 开发者_JS百科dependency property are static and the question still remain on my mind is why we need to use Readonly keyword at the time of declaration of Dependency Property.


Conceptually a dependency property is something that a dependency object simply has and that does not depend on when you use the property. Just like a CLR property, if you ask does this object have a Total property, you know it cannot be a double now but an int later. As a result, we'd make the dependency property const if we could, but we cannot, so readonly is the next best thing.

Using the readonly keyword has at least three effects:

  • it informs readers of the code that the value will not change
  • it prevents the author from accidentally changing the value
  • it assists the compiler, which benefits from knowing when things will not change


Because it makes it obvious, that the value of this property cannot be changed after initialization.


Hopefully this would help: Silverlight.net forums: DependencyProperty - public static readonly?

To quote:

The "public static readonly" is the field that comes back from the Register call. The field is the identifier for the property. You only really need the identifier so that the Silverlight property system knows what to do, and so that you can use the property system yourself as you define the dependency property's CLR "wrapper". Once you have the wrapper, all further usage of the property can just use it like a typical property.

Public so that all property system calls including cross-assembly can access it.

Static and readonly because this isn't a definition that should ever change; the property system needs to get consistent results.

In the attached property case, you want there to be an "owner" class. The owner class must be the class that calls RegisterAttached, AND must also define the static accessor methods (Get* and Set*) so that the XAML parser knows what to do when you try to set the attached property on a DependencyObject instance. So it's a little different, because for an attached property there usually isn't a "wrapper", any code access just uses the Get* and Set* accessors.

0

精彩评论

暂无评论...
验证码 换一张
取 消