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

  • 相关阅读:
    Entity Framework后台采用分页方式取数据与AspNetPager控件的使用
    Excel Interactive View
    让Visual Studio 2013为你自动生成XML反序列化的类
    如何在C#中生成与PHP一样的MD5 Hash Code
    JavaScript text highlighting JQuery plugin
    JQuery文本框水印插件的简单实现
    Chrome浏览器在Windows8/8.1下显示模糊的解决办法
    Sharing count on Facebook, Twitter, and LinkedIn
    Windows 8.1——将网站固定到开始菜单,自定义图标、颜色和Windows推送通知
    [转]php使用 memcache 来存储 session
  • 原文地址:https://www.cnblogs.com/langhua/p/2040723.html
Copyright © 2011-2022 走看看