Why Dependency property are declared as static readonly?

后端 未结 3 2178
傲寒
傲寒 2021-02-20 09:41

It is clear to me why 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 Pro

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-20 09:59

    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.

提交回复
热议问题