Silverlight supports basic data validation in TwoWay bindings for target-to-source updates. Silverlight reports a validation error in the following cases:
Exceptions thrown from the binding engine's type converter.
Exceptions thrown from the binding object's set accessor.
Exceptions thrown from a validation attribute that is applied to a data object or member.
Silverlight provides visual feedback for validation errors when you set the ValidatesOnExceptions property to true on the binding object. The visual feedback indicates the control that contains the error, and displays the error message nearby, as shown in the following illustration.
.png)
You can customize the visual feedback for a control by modifying or replacing its default ControlTemplate. For more information, see Control Customization.
In order to receive notification that a validation error has occurred, you must also set the NotifyOnValidationError property to true on the binding object. Setting ValidatesOnExceptions to true tells the binding engine to create a validation error when an exception occurs. Setting NotifyOnValidationError to true tells the binding engine to raise the BindingValidationError event when a validation error occurs and resolves. For example, you can handle the error event to log the error or provide additional visual feedback.
To handle the BindingValidationError event, create an event handler on the target object or any of its parents. The BindingValidationError event is a routed event, so if you do not handle it on the element that raised the event, it will continue to bubble up until it is handled. For more information on routed events, see Events Overview for Silverlight.
The following example shows how to provide custom binding validation.
The binding is created in XAML.
<StackPanel BindingValidationError="StackPanel_BindingValidationError" >
<StackPanel.Resources>
<my:Bills x:Name="MyBills"/>
</StackPanel.Resources>
<TextBox x:Name="MyTextBox" Width="50" Margin="10">
<TextBox.Text>
<Binding Mode="TwoWay" Source="{StaticResource MyBills}"
Path="Amount" NotifyOnValidationError="true"
ValidatesOnExceptions="true"/>
</TextBox.Text>
</TextBox>
<Button Height="50" Width="150" Content="Click To Update Source"/>
</StackPanel>
The source object throws an exception in the set accessor if the value is negative.
Public Class Bills
Private _Amount As Double
Public Property Amount() As Double
Get
Return _Amount
End Get
Set(ByVal value As Double)
If value < 0 Then
Throw New Exception("Amount must be greater than zero.")
End If
_Amount = value
End Set
End Property
End Class
public class Bills
{
private double _Amount;
public double Amount
{
get { return _Amount; }
set
{
if (value < 0)
throw new Exception("Amount must be greater than zero.");
_Amount = value;
}
}
}
The StackPanel implements a handler for the BindingValidationError event.
Private Sub StackPanel_BindingValidationError(ByVal sender As Object, _
ByVal e As ValidationErrorEventArgs)
If e.Action = ValidationErrorEventAction.Added Then
MyTextBox.Background = New SolidColorBrush(Colors.Red)
ElseIf e.Action = ValidationErrorEventAction.Removed Then
MyTextBox.Background = New SolidColorBrush(Colors.White)
End If
End Sub
private void StackPanel_BindingValidationError(object sender,
ValidationErrorEventArgs e)
{
if (e.Action == ValidationErrorEventAction.Added)
{
MyTextBox.Background = new SolidColorBrush(Colors.Red);
}
else if (e.Action == ValidationErrorEventAction.Removed)
{
MyTextBox.Background = new SolidColorBrush(Colors.White);
}
}
Run this sample
After the sample starts, type in letters instead of numbers to get an error caused by the type converter. Type in a negative number to get an error from the source object's set accessor. Type in a positive number to resolve the validation error. TextBox target-to-source updates occur only when the TextBox loses focus. The button is provided to change the focus. If you prefer, you can update the source manually in response to the button click, as described earlier in the Updating the Data Source section.
For information about applying validation attributes to specify the allowed values for a property or object, see Using Data Annotations to Customize Data Classes. For information about providing more detailed validation reporting, see the ValidationSummary class overview.