Silverlight 3 Quick Tip #9: DataBinding with Validation
Silverlight 3 provides validation mechanism while using Two-Way data binding.
Silverlight 3 also provides default a Validation Exception UI – callout with exception details, which could be customized.
Many input-related controls such as TextBox, CheckBox, etc. have built-in support for validation.
How to use? Simple, like everything with Silverlight: To enable validation, use the ValidatesOnExceptions property.
<TextBox Text="{Binding ID, Mode=TwoWay, ValidatesOnExceptions=True}" />
//Code behind – property definition
public string ID
{
get { return id; }
set
{
if (string.IsNullOrEmpty(value))
throw new Exception("This field can't be empty!");
id = value;
}
}
Example on ListBox:
<ListBox SelectedItem="{Binding Score,Mode=TwoWay,ValidatesOnExceptions=True}">
<sys:String>Best</sys:String>
<sys:String>Good</sys:String>
<sys:String>Ok</sys:String>
<sys:String>Acceptable</sys:String>
<sys:String>Bad</sys:String>
</ListBox>
//Code behind property definition
public string Score
{
get { return score; }
set
{
string[] acceptable = new string[] { "Ok", "Best", "Good" };
if (!acceptable.Contains(value))
throw new Exception("The '" + value + "' is unacceptable");
else if (value == "Ok")
throw new Exception("Ok is not the expected answer");
score = value;
}
}
Sample UI:
Enjoy,
Alex