Wednesday, February 18, 2009

WPF - Validating a dependency property

Validation business rules can be implemented in WPF dependency property by adding a ValidationCallbackHandler when specifying PropertyMetadata options for a DependencyProperty.
The validation method returns a Boolean value mentioning the validation of the property value that is set. The PropertyChangedCallback method is only invoked if the validation rules are passed. This way makes sure that the business rule is validated when using WPF properties.
In the example given below I have used a ValidationCallbackHandler to check whether the user input in the textbox is a positive number or not. If the validation rule fails the ForeColor of the textbox is changed to Red, otherwise the message box is displayed showing that the property was changed successfully.

public static readonly DependencyProperty PositiveNumberProperty = DependencyProperty.Register("PositiveNumber", typeof(int), typeof(Window1),
new PropertyMetadata(0, (x, y) =>
MessageBox.Show("Property changed");
Window1 mainWindow = x as Window1;
if (mainWindow != null)
mainWindow.PositiveNumberTextBox.Foreground = Brushes.Black;
mainWindow.PositiveNumberTextBox.FontWeight = FontWeights.Normal;
}), (x) =>
int positiveValue;
if (int.TryParse(x.ToString(), out positiveValue))
if (positiveValue >= 0)
return true;
return false;

public int PositiveValue
get { return (int)GetValue(PositiveNumberProperty); }
set { SetValue(PositiveNumberProperty, value); }
private void OnValueChanged(object sender, KeyEventArgs e)
TextBox textBox = sender as TextBox;
if (sender != null)
textBox.Foreground = Brushes.Red;
textBox.FontWeight = FontWeights.Bold;
The XAML for the sample is

<Window x:Class="MyWPFSamples.Validation.Window1"
Title="Validating DependencyProperty" Height="300" Width="500"> <StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="16" Margin="6" FontWeight="Bold"> Enter a positive number </TextBlock>
<TextBox x:Name="PositiveNumberTextBox" Margin="6" FontSize="12" Width="150" Text="{Binding Path=PositiveNumber, UpdateSourceTrigger=PropertyChanged}" PreviewKeyDown="OnValueChanged"></TextBox>


No comments: