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

  • 相关阅读:
    企业微信授权微信开发者工具
    liunx Python3中pip3安装模块出错,找不到SSL
    superagent 调用java接口,处理http请求
    Android开发一 application 应用界面主题Theme使用方法
    HTML5的Video标签的属性,方法和事件汇总
    多个select下拉框,选中当前某一项,其他下拉框去掉选中的值
    input range滑块插件 Powerange
    thinkphp 获取session的方法
    thinkphp I()方法获取不到ajax传值
    js验证图片上传大小,格式以及宽高
  • 原文地址:https://www.cnblogs.com/langhua/p/2040723.html
Copyright © 2011-2022 走看看