在Silverlight应用程序中进行数据验证
实例
首先我们编写一个简单的业务类,由于数据绑定验证只能在双向绑定中,所以这里需要实现INotifyPropertyChanged接口,如下代码所示,在set设置器中我们对于数据的合法性进行检查,如果不合法则抛出一个异常:
/// <summary> /// Author:TerryLee /// http://www.cnblogs.com/Terrylee /// </summary> public class Person : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private int _age; public int Age { get { return _age; } set { if (value < 0) throw new Exception("年龄输入不合法!"); _age = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Age")); } } } private String _name = "Terry"; public String Name { get { return _name; } set { if (value.Length < 4) throw new Exception("姓名输入不合法!"); _name = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } } public void NotifyPropertyChanged(String propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }
编写数据绑定,如下代码所示,设置NotifyOnValidationError和ValidatesOnExceptions属性为true,并且定义BindingValidationError事件:
<!-- http://www.cnblogs.com/Terrylee --> <StackPanel Orientation="Horizontal" Margin="10"> <TextBox x:Name="txtName" Width="200" Height="30" Text="{Binding Name,Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" BindingValidationError="txtName_BindingValidationError"> </TextBox> <my:Message x:Name="messageName"></my:Message> </StackPanel> <StackPanel Orientation="Horizontal" Margin="10"> <TextBox x:Name="txtAge" Width="200" Height="30" Text="{Binding Age,Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" BindingValidationError="txtAge_BindingValidationError"> </TextBox> <my:Message x:Name="messageAge"></my:Message> </StackPanel>
实现BindingValidationError事件,在这里可以根据ValidationErrorEventAction来判断如何进行处理,在界面给出相关的提示信息等,如下代码所示:
/// <summary> /// Author:TerryLee /// http://www.cnblogs.com/Terrylee /// </summary> void txtAge_BindingValidationError(object sender, ValidationErrorEventArgs e) { if (e.Action == ValidationErrorEventAction.Added) { messageAge.Text = e.Error.Exception.Message; messageAge.Validation = false; } else if (e.Action == ValidationErrorEventAction.Removed) { messageAge.Text = "年龄验证成功"; messageAge.Validation = true; } }