How Do You Handle Validation In Silverlight?

Aaron Fischer picture Aaron Fischer · Oct 9, 2008 · Viewed 19.7k times · Source

How have you decided to handle data/control validation in your silverlight applications?

Answer

Yuval Peled picture Yuval Peled · Oct 13, 2008

You can throw and capture data validation exceptions.

To manage both of these types of errors need to take 3 steps:

  1. Identify the error handler either in the control or higher in the visiblity hierarchy (e.g., a container; in this case the grid that contains the text box)
  2. Set NotifyOnValidationError and ValidateOnException to true. The latter tells the Binding Engine to create a validation error event when an exception occurs. The former tells the Binding Engine to raise the BindingValidationError event when a validation error occurs.
  3. Create the event handler named in step 1.

Taken from here.

Sample code:

// 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
}