#117 – Registering a Dependency Property
November 6, 2010 2 Comments
To implement a dependency property, a class will create a single static instance of the DependencyProperty class. This instance is static because DependencyProperty just describes the dependency property, rather than being a place to store the actual property value.
You start by declaring a static member for the new property.
public static readonly DependencyProperty AgeProperty;
You typically register the property in a static constructor, using the static DependencyProperty.Register method.
static Person()
{
PropertyMetadata ageMetadata =
new PropertyMetadata(
18, // Default value
new PropertyChangedCallback(OnAgeChanged),
new CoerceValueCallback(OnAgeCoerceValue));
// Register the property
AgeProperty =
DependencyProperty.Register(
"Age", // Property's name
typeof(int), // Property's type
typeof(Person), // Defining class' type
ageMetadata, // Defines default value & callbacks (optional)
new ValidateValueCallback(OnAgeValidateValue)); // validation (optional)
}
The first three parameters passed to Register are required.
You can also specify:
- A default value for the property
- A method to be called when the property value changes
- Coercion and validation callbacks
Pingback: #154 – Reusing an Existing Dependency Property in Your Class « 2,000 Things You Should Know About WPF
Pingback: #155 – Implementing an Attached Dependency Property « 2,000 Things You Should Know About WPF