zoukankan      html  css  js  c++  java
  • 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(thisnullnull);
    14                     tmpValidator.MemberName = "UserName";
    15                     Validator.ValidateProperty(value, tmpValidator);
    16                     _userName = value; 
    17 
    18                 }
    1920 
    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

  • 相关阅读:
    (二)Spring Security 入门体验之——用户密码配置
    (一)Spring Security 入门体验
    (十二)权限之RBAC
    (十一)jwt详解
    (十)登录拦截器之前后端
    (九)优化登录页面
    (八)前后端整合之跨域问题
    SecureCRT 8.1.4 破解教程
    centOS配置网络(6.8)securCRT连接虚拟机
    二叉树的下一个节点(给定一棵二叉树的其中一个节点,请找出中序遍历序列的下一个节点)
  • 原文地址:https://www.cnblogs.com/langhua/p/2040723.html
Copyright © 2011-2022 走看看