Silverlight开发工具对于编程人员来说是一个非常有用的多媒体处理平台。其中有很多功能与应用技巧值得我们去深入的研究。在这里我们就为大家介绍一下有关Silverlight数据验证的实现方法。#t#
首先我们编写一个简单的业务类,由于数据绑定验证只能在双向绑定中,所以这里需要实现INotifyPropertyChanged接口,如下Silverlight数据验证代码所示,在set设置器中我们对于数据的合法性进行检查,如果不合法则抛出一个异常:
- /// < summary>
- /// Author:TerryLee
- /// http://www.cnblogs.com/Terrylee
- /// < /summary>
- public class Person :
INotifyPropertyChanged - {
- public event PropertyChanged
EventHandler 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 Property
ChangedEventArgs(propertyName)); - }
- }
- }
编写Silverlight数据验证,如下代码所示,设置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来判断如何进行处理,在界面给出相关的提示信息等,如下Silverlight数据验证代码所示:
- /// < summary>
- /// Author:TerryLee
- /// http://www.cnblogs.com/Terrylee
- /// < /summary>
- void txtAge_BindingValidationError
(object sender, ValidationErrorEventArgs e)- {
- if (e.Action == ValidationError
EventAction.Added)- {
- messageAge.Text = e.Error.
Exception.Message;- messageAge.Validation = false;
- }
- else if (e.Action == Validation
ErrorEventAction.Removed)- {
- messageAge.Text = "年龄验证成功";
- messageAge.Validation = true;
- }
- }
通过这样的方式,我们就可以实现Silverlight数据验证。