Dependency properties are created specifically for WPF, but the dependency properties in the WPF library are encapsulated using the normal. NET attribute procedure (Property procedure).
1. Defining Dependency Properties
Note: Dependency properties can only be added for dependent objects (classes that inherit from DependencyObject). Fortunately, most of the key parts of the WPF infrastructure are indirectly inherited from the DependencyObject class, the most obvious example being the element.
Dependency properties require information to be shared among multiple classes, so the DependencyProperty object must be defined as a static field of the class associated with it. and by convention, the name of the field of the dependency property is the word "property" at the end of the normal attribute.
1 Public class FrameworkElement 2 {3 Public Static ReadOnly DependencyProperty Marginproperty; 4 }
Description
The definition of a dependency property can be distinguished from the name of the actual attribute by the word "property".
The definition of a field uses the ReadOnly keyword, which means that it can only be set in the static constructor of the FrameworkElement class.
1.2 Registering the dependency property
Defining the DependencyProperty object is only the first step, using the dependency property, and the dependency property created by using WPF registration, and the registration needs to be done before any code that uses the property, so it must be in the static constructor of the class with which it is associated.
WPF ensures that the DependencyProperty object cannot be instantiated directly because the DependencyProperty class does not have a public constructor and can only use static dependencyproperty.register () method to create a DependencyProperty instance.
To declare a dependency property:
1 Public Static ReadOnly DependencyProperty Attachcontentproperty = dependencyproperty.registerattached (2 " attachcontent " typeof (ControlTemplate),typeofnew frameworkpropertymetadata (null));
- Attribute name: attachcontent;
- Data type used by property: ControlTemplate
- The type that owns the property: Controlattachproperty
- A Frameworkpropertymetadata object with attached property settings, which is optional
- A callback function that is used to validate the property, which is optional
Get dependency property:
1 Public Static ControlTemplate Getattachcontent (DependencyObject D) 2 {3 return (ControlTemplate) d.getvalue (attachcontentproperty); 4 }
The Set dependency property:
1 Public Static void setattachcontent (DependencyObject obj, ControlTemplate value) 2 {3 obj. SetValue (attachcontentproperty, value); 4 }
WPF Programming Treasure dependency property (eight)