#122 – Validating a Dependency Property
November 11, 2010 2 Comments
A class that implements a dependency property can optionally provide a validation callback, which it specifies when registering the property. A validation callback is called when a property is about to be set to a new value and returns true or false, indicating whether the new value is valid.
You specify a validation callback when registering a dependency property.
AgeProperty =
DependencyProperty.Register(
"Age", // Property's name
typeof(int), // Property's type
typeof(Person), // Defining class' type
ageMetadata, // Defines default value & changed/coercion callbacks (optional)
new ValidateValueCallback(OnAgeValidateValue)); // *** validation (optional)
The validation callback has the new value passed in.
private static bool OnAgeValidateValue (object value)
{
int age = (int) value;
// Only allow reasonable ages
return (age > 0) && (age < 120);
}
If the property is being set to an invalid value, an exception is thrown.
Person p = new Person("Samuel", "Clemens");
p.Age = 40; // ok
p.Age = 300; // throws System.ArgumentException
Pingback: #133 – Where a Dependency Property Gets Its Value « 2,000 Things You Should Know About WPF
Pingback: #158 – When to Create a Custom Dependency Property « 2,000 Things You Should Know About WPF