一个简单的Demo.百度下载链接:http://pan.baidu.com/s/1sj4oM2h

话不多说,上代码。

1.实体类定义:

class Student : INotifyPropertyChanged, IDataErrorInfo
{
// 用于保存验证错误信息。key 保存所验证的字段名称;value 保存对应的字段的验证错误信息列表
private Dictionary<String, List<String>> errors = new Dictionary<string, List<string>>(); private const string NAME_ERROR = "name 不能包含空格";
private const string ID_ERROR = "id 不能小于 10"; private int age; public int Age
{
get { return age; }
set
{
if (IsIdValid(value))
age = value;
else
age = ;
OnPropertyChanged("Age");
}
} private string stuName;
public string StuName
{
get { return stuName; }
set
{
IsNameValid(value);
stuName = value;
OnPropertyChanged("StuName");
}
} public bool IsIdValid(int value)
{
bool isValid = true; if (value < )
{
AddError("Age", ID_ERROR);
isValid = false;
}
else
{
RemoveError("Age", ID_ERROR);
} return isValid;
} public bool IsNameValid(string value)
{
bool isValid = true; if (String.IsNullOrEmpty(value))
{
AddError("StuName", NAME_ERROR);
isValid = false;
}
else
{
RemoveError("StuName", NAME_ERROR);
} 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 == )
errors.Remove(propertyName);
}
} public string Error
{
get { return errors.Count > ? "有验证错误" : ""; }
} public string this[string propertyName]
{
get
{
if (errors.ContainsKey(propertyName))
return string.Join(Environment.NewLine, errors[propertyName]);
else
return null;
}
} public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
} public event PropertyChangedEventHandler PropertyChanged;
}

Student.cs

2.界面Load绑定:

  拖个errorProvider控件,注意绑定方式。

DataSourceUpdateMode.OnPropertyChanged 可以在属性值改变时进行验证提示。
 public partial class Form1 : Form
{
Student stu = new Student() { StuName = "", Age = };
public Form1()
{
InitializeComponent();
this.textBox1.DataBindings.Add(new Binding("Text", stu, "StuName", false, DataSourceUpdateMode.OnValidation));
this.textBox2.DataBindings.Add(new Binding("Text", stu, "Age", false, DataSourceUpdateMode.OnValidation));
this.errorProvider1.DataSource = stu;
} }

3.判断是否包含错误

直接判断Student对象的Error属性是否为空即可

4.多个实体需要判断,可以抽出个类,根据自己需要扩展对应方法

public class DataErrorInfoCommon
{
// 用于保存验证错误信息。key 保存所验证的字段名称;value 保存对应的字段的验证错误信息列表
public Dictionary<String, List<String>> errors = new Dictionary<string, List<string>>(); public string Error
{
get { return errors.Count > ? "有验证错误" : ""; }
} public string This(string propertyName)
{
if (errors.ContainsKey(propertyName))
return string.Join(Environment.NewLine, errors[propertyName]);
else
return null;
} #region IDataErrorInfo验证方法
private const string REQUIRED = "不能为空";
private const string NUMBER = "请输入数字";
private const string LENGTH_CROSS = "长度超过限制{0}"; /// <summary>
/// 添加错误消息
/// </summary>
/// <param name="propertyName">属性名称</param>
/// <param name="error">错误消息</param>
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);
} /// <summary>
/// 移除错误消息
/// </summary>
/// <param name="propertyName">属性名称</param>
/// <param name="error">错误消息</param>
public void RemoveError(string propertyName, string error)
{
if (errors.ContainsKey(propertyName) && errors[propertyName].Contains(error))
{
errors[propertyName].Remove(error); if (errors[propertyName].Count == )
errors.Remove(propertyName);
}
} /// <summary>
/// 判断是否为空
/// </summary>
/// <param name="propertyName">属性名称</param>
/// <param name="value">属性值</param>
/// <returns></returns>
public bool IsEmpty(string propertyName, string value)
{
bool isEmpty = false;
if (String.IsNullOrWhiteSpace(value))
{
AddError(propertyName, REQUIRED);
isEmpty = true;
}
else
RemoveError(propertyName, REQUIRED);
return isEmpty;
} /// <summary>
/// 判断内容是否是数字
/// </summary>
/// <param name="propertyName">属性名称</param>
/// <param name="value">属性值</param>
/// <returns></returns>
public bool IsNumber(string propertyName, string value)
{
bool isNumber = true;
int num = -;
if (!int.TryParse(value, out num))
{
AddError(propertyName, NUMBER);
isNumber = false;
}
else
RemoveError(propertyName, NUMBER);
return isNumber;
} /// <summary>
/// 判断长度是否超过限制
/// </summary>
/// <param name="propertyName">属性名称</param>
/// <param name="value">属性值</param>
/// <param name="length">长度限制</param>
/// <returns></returns>
public bool IsCrossLenght(string propertyName, string value, int length)
{
bool isCross = false;
if (value.Length > length)
{
AddError(propertyName, string.Format(LENGTH_CROSS, length));
isCross = true;
}
else
RemoveError(propertyName, string.Format(LENGTH_CROSS, length));
return isCross;
}
#endregion
}

5.使用验证类

 //定义验证类对象
public DataErrorInfoCommon dataErrorCommon = null; //在构造函数中初始化
dataErrorCommon =new DataErrorInfoCommon(); //使用
private string stuName;
public string StuName
{
get {
dataErrorCommon.IsEmpty("StuName", stuName);
return stuName;
}
set
{
dataErrorCommon.IsEmpty("StuName",value);
stuName = value;
OnPropertyChanged("StuName");
}
} public event PropertyChangedEventHandler PropertyChanged;
/// 属性改变通知事件
/// </summary>
/// <param name="propertyName">属性通知</param>
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
} public string Error
{
get { return dataErrorCommon.Error; }
} public string this[string propertyName]
{
get
{
return dataErrorCommon.This(propertyName);
}
}

winform + INotifyPropertyChanged + IDataErrorInfo + ErrorProvider实现自动验证功能的更多相关文章

  1. WinForm应用程序中实现自动更新功能

    WinForm应用程序中实现自动更新功能 编写人:左丘文 2015-4-20 近来在给一客户实施ECM系统,但他们使用功能并不是我们ECM制造版提供的标准功能,他们要求对系统作一些定制功能,为了避免因 ...

  2. thinkPHP 表单自动验证功能

    昨天晚上我们老大叫我弄表单自动验证功能,愁了半天借鉴了好多官网的知识,才出来,诶,总之分享一下我自己的成果吧! thinkphp 在Model基类为我们定义了自动验证的函数和正则表达式,我们只需要在对 ...

  3. <转>thinkphp自动验证无效的问题

    新手入门thinkphp,试用自动验证表单输入数据功能,却发现怎么都不能调用自动验证,自动验证无效,原因竟是一个小细节的疏忽,学习一定要细心啊! Action方法: IndexAction下的adds ...

  4. ThinkPHP 自动验证实例

    //array(验证字段1,验证规则,错误提示,[验证条件,附加规则,验证时间]),protected $_validate = array( ); ThinkPHP 自动验证定义的附加规则如下: r ...

  5. tinkphp中的自动验证

    tinkphp是国内非常流行的一个开源框架,国内大小公司都在用的框架.对于初学的好多同学感觉不太好上手,其实并没没有大家想的那么复杂.自动验证功能是thinkphp提高的一种数据验证方法,分为动态和静 ...

  6. thinkphp自动验证无效的问题

    新手入门thinkphp,试用自动验证表单输入数据功能,却发现怎么都不能调用自动验证,自动验证无效,原因竟是一个小细节的疏忽,学习一定要细心啊! Action方法: IndexAction下的adds ...

  7. Winform(C#.NET)自动更新组件的使用及部分功能实现

    声明:核心功能的实现是由园子里圣殿骑士大哥写的,本人是基于他核心代码,按照自己需求进行修改的.   而AutoUpdaterService.xml文件生成工具是基于评论#215楼 ptangbao的代 ...

  8. Winform(C#.NET)自动更新组件的使用及部分功能实现(一点改进功能)

    接前两篇继续: Winform(C#.NET)自动更新组件的使用及部分功能实现 Winform(C#.NET)自动更新组件的使用及部分功能实现(续) 借鉴文章:http://www.cnblogs.c ...

  9. Winform(C#.NET)自动更新组件的使用及部分功能实现(续)

    接昨天的文章Winform(C#.NET)自动更新组件的使用及部分功能实现 强制更新的实现部分: 将DownloadConfirm窗体修改成单纯的类 public class DownloadConf ...

随机推荐

  1. 【vijos】1781 同余方程(拓展欧几里得)

    https://vijos.org/p/1781 学习了下拓欧.. 求exgcd时,因为 a*x1+b*y1=a*x2+b*y2=b*x2+(a-b*[a/b])*y2 然后移项得 a*x1+b*y1 ...

  2. 【python】获取网页中中文内容并分词

    # -*- coding: utf-8 -*- import urllib2 import re import time import jieba url="http://www.baidu ...

  3. C语言程序设计-猴子选大王[链表应用]

    2032 猴子选大王 Description 有N只猴子,从1~N进行编号.它们按照编号的顺时针方向排成一个圆圈,然后从第一只猴子开始报数.第一只猴子报的第一个数字为1,以后每只猴子报的数字都是它们前 ...

  4. [原创]Nexus5 移植OneStep

    OneStep 简介 https://github.com/SmartisanTech/android One Step 涉及的工程列表: frameworks_base (需要更改WindowMan ...

  5. Servlet及相关类和接口

    上一篇介绍了在Web项目中web.xml文件的配置信息,本篇主要介绍里面非常重要的配置——Servlet配置,重点介绍与Servlet相关的几个接口和类,包括Servlet接口.ServletConf ...

  6. mybatis的oracle的in超过1000的写法

    <if test="preIds != null and preIds.size() > 0"> AND PRE_ID IN <trim suffixOve ...

  7. MySQL 索引设计概要

    在关系型数据库中设计索引其实并不是复杂的事情,很多开发者都觉得设计索引能够提升数据库的性能,相关的知识一定非常复杂. 然而这种想法是不正确的,索引其实并不是一个多么高深莫测的东西,只要我们掌握一定的方 ...

  8. oracle mysql sqlserver 基本操作命令

    1.oracle (1) 启动 监听 lsnrctl start: (2)进入sqlplus界面 sqlplus  /nolog SQL>conn sys/jiaxiaoai@orcl as s ...

  9. MyISAM Key Buffer 读/写/利用率(%) MylSAM平均每秒Key Buffer利用率(%) MylSAM平均每秒Key Buffer读命中率(%) MylSAM平均每秒Key Buffer写命中率(%)

    MyISAM Key Buffer 读/写/利用率(%) MylSAM平均每秒Key Buffer利用率(%)MylSAM平均每秒Key Buffer读命中率(%)MylSAM平均每秒Key Buff ...

  10. Apache Tez Design

    http://tez.incubator.apache.org/ http://dongxicheng.org/mapreduce-nextgen/apache-tez/ http://dongxic ...