You can create exceptions to validate data.
To manage these two types of errors, you must complete 3 steps:
- Define an error handler either in the control or higher in the visibility hierarchy (for example, in a container, in this case a grid containing a text field)
- Set the value of NotifyOnValidationError and ValidateOnException to true. The latter tells the Binding Engine to raise a validation error event when an exception occurs. The first tells the Binding Engine to raise a BindingValidationError event when a validation error occurs.
- Create the event handler specified in step 1.
Taken from here .
Code example:
// page.xaml.cs private bool clean = true; private void LayoutRoot_BindingValidationError( object sender, ValidationErrorEventArgs e ) { if ( e.Action == ValidationErrorEventAction.Added ) { QuantityOnHand.Background = new SolidColorBrush( Colors.Red ); clean = false; } else if ( e.Action == ValidationErrorEventAction.Removed ) { QuantityOnHand.Background = new SolidColorBrush( Colors.White ); clean = true; } } // page.xaml <Grid x:Name="LayoutRoot" Background="White" BindingValidationError="LayoutRoot_BindingValidationError" > <TextBox x:Name="QuantityOnHand" Text="{Binding Mode=TwoWay, Path=QuantityOnHand, NotifyOnValidationError=true, ValidatesOnExceptions=true }" VerticalAlignment="Bottom" HorizontalAlignment="Left" Height="30" Width="90"red Grid.Row="4" Grid.Column="1" /> // book.cs public int QuantityOnHand { get { return quantityOnHand; } set { if ( value < 0 ) { throw new Exception( "Quantity on hand cannot be negative!" ); } quantityOnHand = value; NotifyPropertyChanged( "QuantityOnHand" ); } // end set }
source share