Siverlight异步数据验证二

本文介绍的是DataAnnotation验证机制,利用RIA service提供的验证机制,

需要引入名称空间:

using System.ComponentModel.DataAnnotations;

本文以填写用户名和密码为例简单说明必填验证的方法.

验证类如下:

 

 1           private   string  _userName;
 2          [Required(ErrorMessage  =   " 必填选项 " )]
 3           public   string  UserName
 4          {
 5               get  {  return  _userName; }
 6               set
 7              {
 8                   if  (_userName != value)
 9                  {
10                       // _userName = value;
11                       // NotifyPropertyChanged("UserName");
12 
13                      var tmpValidator  =   new  ValidationContext( this null null );
14                      tmpValidator.MemberName  =   " UserName " ;
15                      Validator.ValidateProperty(value, tmpValidator);
16                      _userName  =  value; 
17 
18                  }
19 20 
21              }
22          }

客户端设置如下:

第一步引入:

xmlns:local="clr-namespace:SilverlightApplication2"

第二步

<local:User x:Key="userDataContext"/>

第三步绑定数据源

 

1           < TextBox  Grid.Column ="1"  Height ="30"  HorizontalAlignment ="Left"  Margin ="28,57,0,0"  Name ="textBox1"  DataContext =" {Binding Source={StaticResource userDataContext}} "  Text =" {Binding UserName,Mode=TwoWay,NotifyOnValidationError=True,ValidatesOnExceptions=True} "  VerticalAlignment ="Top"  Width ="158"   />
2           < TextBox  Height ="30"  HorizontalAlignment ="Left"  Margin ="28,55,0,0"  Name ="textBox2"   DataContext =" {Binding Source={StaticResource userDataContext}} "  Text =" {Binding Password,Mode=TwoWay,NotifyOnValidationError=True,ValidatesOnExceptions=True} "  VerticalAlignment ="Top"  Width ="158"  Grid.Column ="1"  Grid.Row ="1"   />

 

第四步,捕获

 

 1           private   void  LayoutRoot_BindingValidationError( object  sender, ValidationErrorEventArgs e)
 2          {
 3               if  (e.Action  ==  ValidationErrorEventAction.Added)
 4              {
 5                  (e.OriginalSource  as  Control).Background  =   new  SolidColorBrush(Colors.Yellow);
 6                  tbMessage.Text  =  e.Error.Exception.Message;
 7              }
 8 
 9               if  (e.Action  ==  ValidationErrorEventAction.Removed)
10              {
11                  (e.OriginalSource  as  Control).Background  =   new  SolidColorBrush(Colors.White);
12                  tbMessage.Text  =   "" ;
13              }
14          }

 

效果如下:

下载Demo

转载于:https://www.cnblogs.com/langhua/archive/2011/05/09/2040723.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值