原文地址:http://www.cnblogs.com/webabcd/archive/2010/09/09/1821911.html

介绍
Silverlight 4.0 数据验证:

  • IDataErrorInfo - 对数据实体类提供自定义验证支持。.NET Framework 也有此接口,可以方便移植
  • INotifyDataErrorInfo - 对数据实体类提供自定义验证支持,比 IDataErrorInfo 功能更强大。INotifyDataErrorInfo 支持异步验证,这就意味着其可以通过验证方法调用 Web 服务和用回调方法更新错误集合来添加服务器端验证

示例
1、演示 IDataErrorInfo 的应用
IDataErrorInfoModel.cs

/*
 * IDataErrorInfo - 对数据实体类提供自定义验证支持。.NET Framework 也有此接口,可以方便移植
 *     string Error - 获取对象的验证错误信息
 *     string this[string columnName] - 获取对象的指定字段的验证错误信息
 */

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Silverlight40.Binding
{
    public class IDataErrorInfoModel : System.ComponentModel.IDataErrorInfo
    {
        // 验证错误的提示信息
        private const string ID_ERROR = "id 不能小于 10";
        private const string NAME_ERROR = "name 不能包含空格";
        private const string NAME_WARNING = "name 不能小于 5 个字符";

// 用于保存验证错误信息。key 保存所验证的字段名称;value 保存对应的字段的验证错误信息列表
        private Dictionary<String, List<String>> errors = new Dictionary<string, List<string>>();

private int _id;
        [Display(Name = "标识")]
        public int Id
        {
            get { return _id; }
            set 
            {
                if (value > 1000)
                    throw new Exception("太大了");

if (IsIdValid(value) && _id != value) 
                    _id = value; 
            }
        }

private string _name;
        [Display(Name = "名称")]
        public string Name
        {
            get { return _name; }
            set 
            { 
                if (IsNameValid(value) && _name != value) 
                    _name = value; 
            }
        }

public bool IsIdValid(int value)
        {
            bool isValid = true;

if (value < 10)
            {
                AddError("Id", ID_ERROR);
                isValid = false;
            }
            else
            {
                RemoveError("Id", ID_ERROR);
            }

return isValid;
        }

public bool IsNameValid(string value)
        {
            bool isValid = true;

if (value.Contains(" "))
            {
                AddError("Name", NAME_ERROR);
                isValid = false;
            }
            else
            {
                RemoveError("Name", NAME_ERROR);
            }

if (value.Length < 5)
            {
                AddError("Name", NAME_WARNING);
                isValid = false;
            }
            else
            {
                RemoveError("Name", NAME_WARNING);
            }

return isValid;
        }
      
        public void AddError(string propertyName, string error)
        {
            if (!errors.ContainsKey(propertyName))
                errors[propertyName] = new List<string>();

if (!errors[propertyName].Contains(error))
                errors[propertyName].Add(error);
        }

public void RemoveError(string propertyName, string error)
        {
            if (errors.ContainsKey(propertyName) && errors[propertyName].Contains(error))
            {
                errors[propertyName].Remove(error);

if (errors[propertyName].Count == 0) 
                    errors.Remove(propertyName);
            }
        }

public string Error
        {
            get { return errors.Count > 0 ? "有验证错误" : "没有验证错误"; }
        }

public string this[string propertyName]
        {
            get 
            {
                if (errors.ContainsKey(propertyName))
                    return string.Join(Environment.NewLine, errors[propertyName]);
                else
                    return null;
            }
        }
    }
}

IDataErrorInfo.xaml

<navigation:Page x:Class="Silverlight40.Binding.IDataErrorInfo" 
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
           Title="IDataErrorInfo Page">
    <Grid x:Name="LayoutRoot">
        <StackPanel HorizontalAlignment="Left">

<sdk:ValidationSummary Margin="3">
                <sdk:ValidationSummary.Header>
                    错误列表:
                </sdk:ValidationSummary.Header>
            </sdk:ValidationSummary>

<!--
                ValidatesOnExceptions - 指定绑定引擎是否报告验证过程中的异常信息
                ValidatesOnDataErrors - 指定绑定引擎是否报告绑定数据实体上的 IDataErrorInfo 所实现的验证错误信息(通过 IDataErrorInfo 的 this[string columnName] 获取验证错误信息)
                NotifyOnValidationError - 当出现验证错误时是否触发 BindingValidationError 事件
            -->
            <StackPanel Orientation="Horizontal">
                <sdk:Label Target="{Binding ElementName=txtId}" />
                <TextBox Name="txtId" Text="{Binding Id, Mode=TwoWay, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" KeyDown="txtId_KeyDown"/>
                <sdk:DescriptionViewer Description="id 不能小于 10"/>
            </StackPanel>

<StackPanel Orientation="Horizontal">
                <sdk:Label Target="{Binding ElementName=txtName}"/>
                <TextBox Name="txtName" Text="{Binding Name, Mode=TwoWay, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" KeyDown="txtName_KeyDown"/>
                <sdk:DescriptionViewer Description="name 不能包含空格且 name 不能小于 5 个字符"/>
            </StackPanel>
            
            <Button Name="btnSubmit" Content="获取验证信息" Click="btnSubmit_Click" />
            
        </StackPanel>
    </Grid>
</navigation:Page>

IDataErrorInfo.xaml.cs

/*
 * 通过绑定实现了 IDataErrorInfo 接口的实体类来实现自定义数据验证功能
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

namespace Silverlight40.Binding
{
    public partial class IDataErrorInfo : Page
    {
        IDataErrorInfoModel _model;

public IDataErrorInfo()
        {
            InitializeComponent();
        }

protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            _model = new IDataErrorInfoModel() { Id = 100, Name = "webabcd" };
            LayoutRoot.DataContext = _model;

// BindingValidationError - 当有数据验证错误时所触发的事件。绑定时需要设置 NotifyOnValidationError=True
            txtId.BindingValidationError += (x, y) => { MessageBox.Show(y.Error.ErrorContent.ToString()); };
            txtName.BindingValidationError += (x, y) => { MessageBox.Show(y.Error.ErrorContent.ToString()); };
        }

private void txtId_KeyDown(object sender, KeyEventArgs e)
        {
            // 注:
            // BindingValidationError 事件只有在控件失去焦点才会被触发
            // 如果需要在控件没失去焦点的情况下产生验证效果,那么可以通过调用 BindingExpression.UpdateSource() 方法来实现

// FrameworkElement.GetBindingExpression(DependencyProperty dp) - 获取 FrameworkElement 的指定属性上的绑定信息
            // BindingExpression.UpdateSource() - 将当前绑定信息立即发送到绑定方式为 TwoWay 的属性上
            if (e.Key == System.Windows.Input.Key.Enter)
                txtId.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        }

private void txtName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
                txtName.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        }

private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("验证信息:" + _model.Error);
        }
    }
}

2、演示 INotifyDataErrorInfo 的应用
INotifyDataErrorInfoModel.cs

/*
 * INotifyDataErrorInfo - 对数据实体类提供自定义验证支持,比 IDataErrorInfo 功能更强大。INotifyDataErrorInfo 支持异步验证,这就意味着其可以通过验证方法调用 Web 服务和用回调方法更新错误集合来添加服务器端验证
 *     bool HasErrors - 对象是否有验证错误信息
 *     event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged - 当对象的验证错误信息发生改变时所触发的事件
 *     IEnumerable GetErrors(string propertyName) - 获取对象的指定字段的验证错误信息
 */

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace Silverlight40.Binding
{
    public class INotifyDataErrorInfoModel : System.ComponentModel.INotifyDataErrorInfo
    {
        // 验证错误的提示信息
        private const string ID_ERROR = "id 不能小于 10";
        private const string NAME_ERROR = "name 不能包含空格";
        private const string NAME_WARNING = "name 不能小于 5 个字符";

// 用于保存验证错误信息。key 保存所验证的字段名称;value 保存对应的字段的验证错误信息列表
        private Dictionary<String, List<String>> errors = new Dictionary<string, List<string>>();

private int _id;
        [Display(Name = "标识")]
        public int Id
        {
            get { return _id; }
            set
            {
                if (value > 1000)
                    throw new Exception("太大了");

if (IsIdValid(value) && _id != value)
                    _id = value;
            }
        }

private string _name;
        [Display(Name = "名称")]
        public string Name
        {
            get { return _name; }
            set
            {
                if (IsNameValid(value) && _name != value)
                    _name = value;
            }
        }

public bool IsIdValid(int value)
        {
            bool isValid = true;

if (value < 10)
            {
                AddError("Id", ID_ERROR);
                isValid = false;
            }
            else
            {
                RemoveError("Id", ID_ERROR);
            }

return isValid;
        }

public bool IsNameValid(string value)
        {
            bool isValid = true;

if (value.Contains(" "))
            {
                AddError("Name", NAME_ERROR);
                isValid = false;
            }
            else
            {
                RemoveError("Name", NAME_ERROR);
            }

if (value.Length < 5)
            {
                AddError("Name", NAME_WARNING);
                isValid = false;
            }
            else
            {
                RemoveError("Name", NAME_WARNING);
            }

return isValid;
        }

public void AddError(string propertyName, string error)
        {
            if (!errors.ContainsKey(propertyName))
                errors[propertyName] = new List<string>();

if (!errors[propertyName].Contains(error))
            {
                errors[propertyName].Add(error);
                RaiseErrorsChanged(propertyName);

}
        }

public void RemoveError(string propertyName, string error)
        {
            if (errors.ContainsKey(propertyName) && errors[propertyName].Contains(error))
            {
                errors[propertyName].Remove(error);

if (errors[propertyName].Count == 0)
                    errors.Remove(propertyName);

RaiseErrorsChanged(propertyName);
            }
        }

public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
        public void RaiseErrorsChanged(string propertyName)
        {
            if (ErrorsChanged != null)
                ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }

public System.Collections.IEnumerable GetErrors(string propertyName)
        {
            if (errors.ContainsKey(propertyName))
                return errors[propertyName];
            else
                return null;
        }

public bool HasErrors
        {
            get { return errors.Count > 0; }
        }
    }
}

INotifyDataErrorInfo.xaml

<navigation:Page x:Class="Silverlight40.Binding.INotifyDataErrorInfo" 
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
           Title="INotifyDataErrorInfo Page">
    <Grid x:Name="LayoutRoot">
        <StackPanel HorizontalAlignment="Left">

<sdk:ValidationSummary Margin="3">
                <sdk:ValidationSummary.Header>
                    错误列表:
                </sdk:ValidationSummary.Header>
            </sdk:ValidationSummary>

<!--
                ValidatesOnExceptions - 指定绑定引擎是否报告验证过程中的异常信息
                NotifyOnValidationError - 当出现验证错误时是否触发 BindingValidationError 事件
            -->
            <StackPanel Orientation="Horizontal">
                <sdk:Label Target="{Binding ElementName=txtId}" />
                <TextBox Name="txtId" Text="{Binding Id, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" KeyDown="txtId_KeyDown"/>
                <sdk:DescriptionViewer Description="id 不能小于 10"/>
            </StackPanel>

<StackPanel Orientation="Horizontal">
                <sdk:Label Target="{Binding ElementName=txtName}"/>
                <TextBox Name="txtName" Text="{Binding Name, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" KeyDown="txtName_KeyDown"/>
                <sdk:DescriptionViewer Description="name 不能包含空格且 name 不能小于 5 个字符"/>
            </StackPanel>

<Button Name="btnSubmit" Content="是否有验证错误" Click="btnSubmit_Click" />

</StackPanel>
    </Grid>
</navigation:Page>

INotifyDataErrorInfo.xaml.cs

/*
 * 通过绑定实现了 INotifyDataErrorInfo 接口的实体类来实现自定义数据验证功能
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

namespace Silverlight40.Binding
{
    public partial class INotifyDataErrorInfo : Page
    {
        INotifyDataErrorInfoModel _model;

public INotifyDataErrorInfo()
        {
            InitializeComponent();
        }

protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            _model = new INotifyDataErrorInfoModel() { Id = 100, Name = "webabcd" };
            LayoutRoot.DataContext = _model;

// BindingValidationError - 当有数据验证错误时所触发的事件。绑定时需要设置 NotifyOnValidationError=True
            txtId.BindingValidationError += (x, y) => { MessageBox.Show(y.Error.ErrorContent.ToString()); };
            txtName.BindingValidationError += (x, y) => { MessageBox.Show(y.Error.ErrorContent.ToString()); };
        }

private void txtId_KeyDown(object sender, KeyEventArgs e)
        {
            // 注:
            // BindingValidationError 事件只有在控件失去焦点才会被触发
            // 如果需要在控件没失去焦点的情况下产生验证效果,那么可以通过调用 BindingExpression.UpdateSource() 方法来实现

// FrameworkElement.GetBindingExpression(DependencyProperty dp) - 获取 FrameworkElement 的指定属性上的绑定信息
            // BindingExpression.UpdateSource() - 将当前绑定信息立即发送到绑定方式为 TwoWay 的属性上
            if (e.Key == System.Windows.Input.Key.Enter)
                txtId.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        }

private void txtName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
                txtName.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        }

private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("是否有验证错误:" + _model.HasErrors.ToString());
        }
    }
}

转载于:https://www.cnblogs.com/arongbest/archive/2011/10/08/2201875.html

SilverLight4.0数据验证IDataErrorInfo, INotifyDataErrorInfo[转]相关推荐

  1. (转)Silverlight数据校验之INotifyDataErrorInfo

    原文地址:http://www.cnblogs.com/PerfectSoft/archive/2012/03/01/2375007.html 在Silverlight中,数据实体类的有效性校验有多种 ...

  2. Scott Mitchell 的ASP.NET 2.0数据教程之三十九:: 在编辑和插入界面里添加验证控件...

    原文 | 下载本教程中的编码例子 | 下载本教程的PDF版 导言 到目前为止的讨论编辑DataList的教程里,没有包含任何验证用户的输入,即使是用户非法输入- 遗漏了product的name或者负的 ...

  3. ASP.NET MVC 入门8、ModelState与数据验证

    ViewData有一个ModelState的属性,这是一个类型为ModelStateDictionary的ModelState类型的字典集合.在进行数据验证的时候这个属性是比较有用的.在使用Html. ...

  4. Silverlight - Validation 客户端同步数据验证

    前文介绍过Silverlight Validation中两个数据验证机制,ValidatesOnExceptions异常捕获验证机制和DataAnnotation验证机制,这两种验证机制,是在Silv ...

  5. Silverlight实例教程 - Validation用户提交数据验证捕获

    在以往的Validation系列中,介绍了四种Silverlight验证机制: 基本异常验证机制: DataAnnotation验证机制: IDataErrorInfo客户端同步验证机制: INoti ...

  6. java中mypoiexception,java - 如何使用Poi获取Java中单元格的数据验证源? - 堆栈内存溢出...

    此问题包含多个不同的问题. 首先,我们需要获取工作表的数据验证,然后为每个数据验证获取数据验证所适用的Excel单元格范围. 如果该单元格位于该单元格范围之一中,并且数据验证是列表约束,则进行进一步处 ...

  7. ExtJs 备忘录(3)—— Form表单(三) [ 数据验证 ]

    正文 一.资料 1.1. 表单提示的方式设置,如: Ext.form.Field.prototype.msgTarget='side' 该设置为枚举值:'qtip','side','title','u ...

  8. day22-Model数据验证以及钩子

    一.前言 其实在django内部也是支持数据验证的,只是这个数据验证比较弱而已,只能支持单个的验证,但是对于组合的,或者固定的,我们就验证不了,你说可以验证邮箱格式,但是不能验证 不能@qq.com结 ...

  9. flask中的CBV , flask-session在redis中存储session , WTForms数据验证 , 偏函数 , 对象里的一些小知识...

    flask中的CBV , flask-session在redis中存储session , WTForms数据验证 , 偏函数 , 对象里的一些小知识 flask中的CBV写法 后端代码 # 导入vie ...

最新文章

  1. 4月29日监理师课程作业
  2. centerandzoom 无效_百度地图 app 点击事件无效、不触发 解决方案
  3. PyTorch随笔-0
  4. 使用mysql做saas_一种SaaS企业平台数据库系统及其连接方法与流程
  5. matlab单元数组和结构,Matlab使用单元数组和结构数组
  6. 在ASP.NET 中实现单用户登录(利用Cache, 将用户信息保存在服务器缓存中)[转]
  7. Ubuntu 安装R/Rstudio
  8. 计算机中什么是以二进制表示的信息,计算机计算各种信息-为什么计算机中的所有信息都以二进制方式表示 – 手机爱问...
  9. 斐波那契数列n项的值。(递归和非递归算法Golang实现)
  10. 屏幕颜色拾取器 (VC++)
  11. 共享WiFi码项目一天赚3000,一个月6W,背后逻辑与源代码分析
  12. docker配置代理pull报错:proxyconnect tcp: tls: first record does not look like a TLS handshake
  13. 引入echarts 报错xAxis “0“ not found
  14. 推荐学习-Linux性能优化实战
  15. BAT 面试题:25匹马,5个跑道,每个跑道最多能有1匹马进行比赛,最少比多少次能比出前3名?前5名?
  16. [11] 微信公众帐号开发教程第11篇-符号表情的发送(上)
  17. 息县装修“茶几的选择”
  18. 工业三防平板可应用于各种复杂苛刻的工作环境
  19. 7-3 求最小码距 (10 分)
  20. 致力于推动植物性食品革命的可持续性食品科技公司——BENSON HILL将与STAR PEAK CORP II合并

热门文章

  1. 7/7 SELECT语句:创建计算字段
  2. WINDOW下,node.js的安装
  3. [POI2015]CZA
  4. 【XSY2111】Chef and Churus 分块 树状数组
  5. Django进阶Model篇—数据库操作(ORM)
  6. python 中爬虫的运用
  7. 成员变量的初始化和内存中的运行机制
  8. monkey的具体使用及详细说明
  9. 界限的应用开发 HTML5,更高效地到达更多设备和用户
  10. 深入探究VC —— 链接器link.exe(4)【转】http://blog.csdn.net/wangningyu/article/details/4849452...