public static readonly DependencyProperty AgeProperty = DependencyProperty.Register( "Age", typeof(int), typeof(Person), new PropertyMetadata(default(int)), ValidateAge); private static bool ValidateAge(object value) { int age = (int)value; return age >= 0 && age <= 120; } public int Age { get { return (int)GetValue(AgeProperty); } set { SetValue(AgeProperty, value); } }
public static readonly DependencyProperty TextProperty = DependencyProperty.Register( "Text", typeof(string), typeof(TextBox), new PropertyMetadata(default(string)), ValidateText); private static bool ValidateText(object value) { string text = (string)value; return !string.IsNullOrWhiteSpace(text) && text.Length <= 100; } public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } }In the above example, we define a validate text method that checks if the text value is not null or empty and its length does not exceed 100 characters. We then use this method to validate the text value whenever it is set using the Text property. Both code examples use the System.Windows library package.