Silverlight:Validation

SilverlightValidation

 

Validation验证概述

       Validation是验证、校验的意思,通常发生在用户输入数据后,进行数据格式的验证,以保证录入信息的正确性。

      我们可以把Validation分为两种验证类型来理解:

(1)  语法验证

语法验证类型是通过成员的数据类型对比当前的输入数据类型得出的验证结果。

(例如:在年龄输入框中输入字符,它们的数据类型不同,就会产生异常)

语法验证经常发生在数据改变之前,其表现方式会在UI中体现。

(2)  语义验证

语义验证类型是将当前输入数据根据特定数据限制代码进行验证。

(例如:Email地址的验证,特定格式的验证)

语义验证通常会发生在数据改变之后,其表现方式可以由开发人员控制,不一定表现在UI中。

 

Validation数据验证框架基础属性和事件

      BindingValidationError 事件

该事件是一个路由事件,当数据验证错误出现时,将绑定该错误到数据源;也可以简单的理解为绑定错误到数据源的一个行为。该事件可在控件本身调用,也可在其父控件中调用。例如,在TextBox中,可以声明调用BindingValidationError,或者可以该TextBox的父容器控件GridStackPanel中调用BindingValidationError事件。这里需要注意的是,如果在SilverlightMVVM设计模式下,仅在被验证的控件本身激活BindingValidationError事件,才能正常的被UI捕获到错误信息,不支持在父控件中对BindingValidationError事件进行调用。为了保证Validation的灵活性,微软同时提供了相关属性,来控制BindingValidationError事件的调用。NotifyOnValidationErrorValidatesOnExceptions属性。

NotifyOnValidationError 属性

该属性的功能,是当验证错误出现时是否激活BindingValidationError事件;该属性是Silverlight独有的验证属性之一,经常和ValidatesOnExceptions属性配合使用。

ValidatesOnExceptions 属性

该属性的功能,数据绑定引擎是否捕获显示异常错误作为验证错误。简单的理解,在控件绑定数据时,出现数据源异常抛出,或者数据类型转换时异常抛出,是否作为Validation验证显示在客户端。如果是True,则会按照Validation传统的处理方式,弹出一个红色说明标签,内容是异常错误信息,反之,则不捕获异常作为Validation

 System.ComponentModel.DataAnnotations

  关于 System.ComponentModel.DataAnnotations ,请去:http://msdn.microsoft.com/zh-cn/library/cc490428(v=VS.95).aspx

示例:以一个用户注册模块为示例

步骤一:在建立好的Silverlight项目下,增加一个User类,代码如下:  

public class User : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string userName;
        public string UserName 
        {
            get 
            {
                return this.userName;
            }
            set 
            {
                Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "UserName" });
                if (string.IsNullOrEmpty(value))
                {
                    throw new Exception("用户名不能为空.");
                }
                NotifyPropertyChanged("UserName");
                this.userName = value;
            }
        }

        private string password;
        [StringLength(6,ErrorMessage="密码长度不能超过 6 个字符.")]
        public string Password 
        {
            get 
            {
                return this.password;
            }
            set 
            {
                Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Password" });
                this.password = value;
            }
        }

        private int age;
        [Range(0,120,ErrorMessage="年龄值必须在 0-120 之间.")]
        public int Age 
        {
            get 
            {
                return this.age;
            }
            set 
            {
                Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Age" });
                this.age = value;
            }
        }

        private string email;
        [RegularExpression(@"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$",ErrorMessage="Email 格式不正确.")]
        public string Email
        {
            get 
            {
                return this.email;
            }
            set 
            {
                var tmpValidator = new ValidationContext(this, null, null);
                tmpValidator.MemberName = "Email";
                Validator.ValidateProperty(value, tmpValidator);
            }
        }

        private void NotifyPropertyChanged(string propertyName) 
        {
            if (PropertyChanged != null) 
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

步骤二:在MainPage.xaml中设计用户注册模块界面,前台代码如下:

<Grid x:Name="LayoutRoot" Background="White" Loaded="LayoutRoot_Loaded" BindingValidationError="LayoutRoot_BindingValidationError">
        <StackPanel Orientation="Vertical" Margin="10">
            <StackPanel Orientation="Horizontal" Margin="5">
                <TextBlock Text="用户名:" FontFamily="Comic Sans MS" FontSize="16"/>
                <TextBox x:Name="UserName" FontFamily="Comic Sans MS" FontSize="15" Width="180" Text="{Binding Path=UserName,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=True}"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal" Margin="5">
                <TextBlock Text="密   码:" FontFamily="Comic Sans MS" FontSize="16"/>
                <TextBox x:Name="Password" FontFamily="Comic Sans MS" FontSize="15" Width="180" Text="{Binding Path=Password,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=True}"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal" Margin="5">
                <TextBlock Text="年   龄:" FontFamily="Comic Sans MS" FontSize="16"/>
                <TextBox x:Name="Age" FontFamily="Comic Sans MS" FontSize="15" Width="180" Text="{Binding Path=Age,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=True}"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal" Margin="5">
                <TextBlock Text="邮   箱:" FontFamily="Comic Sans MS" FontSize="16"/>
                <TextBox x:Name="Email" FontFamily="Comic Sans MS" FontSize="15" Width="180" Text="{Binding Path=Email,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=True}"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <Button x:Name="btLogin" Content="注 册" Height="30" Width="60" FontFamily="Comic Sans MS" FontSize="15" Margin="5" />
            </StackPanel>
        </StackPanel>
    </Grid>

后台代码如下:

public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
            this.LayoutRoot.DataContext = new User();
        }

        private void LayoutRoot_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
            {
                (e.OriginalSource as Control).Background = new SolidColorBrush(Colors.Yellow);
            }

            if (e.Action == ValidationErrorEventAction.Removed)
            {
                (e.OriginalSource as Control).Background = new SolidColorBrush(Colors.White);
            }
        }
    }

本文借鉴于:Silverlight实例教程 - Validation验证系列汇总

posted @ 2011-07-26 17:24  sl-rabassaire  阅读(600)  评论(0)    收藏  举报