In this article we discuss the data validation related knowledge in SL3.
Data validation occurs only in the case of two-way binding, because the entity class needs to implement the INotifyPropertyChanged interface. When data is bound in SL, it is often ignored if it encounters data that is not validated. The following table lists three types of errors when you bind in a two-way way:
1, incorrect data. For example: should be a numeric type, should not enter characters or other characters, at the same time, can not exceed the maximum value.
2, the set exception of the property of the object. For example, there is a judgment in the set of the property ID, and an exception is thrown if there is a problem.
3, read-only properties, you can not perform assignment operation.
If it's the above error, you can't ignore them, because SL data binding won't give you any visual cues. The incorrect value is persisted in the bound control, but is not applied to the binding object.
A good way to avoid this problem is to alert the user in a timely manner and enter a problem. The easiest way to do this is to use the two properties of the bound object, Validatesonexceptions, NotifyOnValidationError, which activates the SL error reminder event.
1, Validatesonexception
Validatesonexception is the first step in implementing other validations. After you set up validatesonexception=true, data binding will respond to any error, whether it appears in type conversions or property setters. However, data binding does not prompt for any errors after you set Validatesonexception=false (the default is False). The bound object is not updated, and the wrong value remains in the bound control.
The following is an example of the settings for a bound control
<TextBox x:Name="customerId" Grid.Column="1" Grid.Row="1" Text="{Binding CustomerId, Mode=TwoWay, ValidatesOnExceptions=true}"></TextBox>
After this setting, your control will be able to capture and display errors after bidirectional binding, which includes the ability to control.
* TextBox
* PasswordBox
* CheckBox
* RadioButton
* ListBox
* ComboBox
Knowledge Point: Verify the status validationstate includes three kinds: Valid, invalidunfocused, invalidfocused.
Here we add validation to the setter of a property,
Code
public virtual int CustomerId
{
get { return this._intCustomerId; }
set
{
int result;
if (Int32.TryParse(value.ToString(), out result) == false)
throw new ArgumentException("必须是数字");
this._intCustomerId = result;
OnPropertyChanged("CustomerId");
}
}