WPF: What distinguishes a Dependency Property from a regular CLR Property?

前端 未结 4 1443
日久生厌
日久生厌 2020-12-08 12:15

In WPF, what, really, does it mean to be a \"dependency property\"?

I read Microsoft\'s Dependency Properties Overview, but it\'s not really sinking in for me. In p

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 13:06

    In WPF, what, really, does it mean to be a "dependency property"?

    In order to be a dependency property, the property must actually be defined as a DependencyProperty, statically, on the class. The dependency property system is very different than a standard CLR property.

    Dependency properties are handled very differently, though. A type defines a dependency property statically, and provides a default value. The runtime actually doesn't generate a value for an instance until it's needed. This provides one benefit - the property doesn't exist until requested for a type, so you can have a large number of properties without overhead.

    This is what makes the styling work property, but is also important to allow attached properties, property "inheritance" through the visual tree, and many other things WPF relies on.

    For example, take the DataContext dependency property. Typically, you set the DataContext dependency property for a Window or a UserControl. All of the controls within that Window, by default, "inherit" their parent's DataContext proeprty automatically, which allows you to specify data bindings for controls. With a standard CLR property, you'd need to define that DataContext for every control in the window, just to get binding to work properly.

提交回复
热议问题