How have you decided to handle data/control validation in your silverlight applications?
+4
A:
You can throw and capture data validation exceptions.
To manage both of these types of errors need to take 3 steps:
- 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)
- 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.
- 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
}
Yuval Peled
2008-10-13 19:25:01
I was expecting to see which control caused the exception in the ValidationErrorEventArgs (http://msdn.microsoft.com/en-us/library/system.windows.controls.validationerroreventargs.aspx). So I moved the BindingValidationError event off the Grid, and onto the textboxes which can cause an exception. This way I can check which control caused in the exception in the sender parameter.
russau
2009-07-01 04:16:36
A:
You might want to look at PostSharp, it makes attributing your client-side data model very simple.
Craig Nicholson
2008-10-19 21:05:10
If you provide an example of how to use PostSharp to aid in validation, then I'll remove the downvote.
Andrew Garrison
2010-01-04 16:23:43
+1
A:
If you are experiencing problems trying to implement this, it's not because your code is broken, it's because the feature is broken in the DataGrid. Check out the article by Jesse Liberty here.
The correct link: http://jesseliberty.com/2008/10/22/it-aint-you-babe%E2%80%A6-a-not-a-bug-bug-in-datagrid/
Lukas Cenovsky
2010-05-07 20:25:37