C# 通用验证类 支持 WPF,MVC,Winform
2013-07-08 15:58
239 查看
验证方式, 通过继承 IDataErrorInfo接口 和 DataAnnotations 解释标记语言而实现,
为了能在WPF上通用,所了也要继承属性更改通知接口INotifyPropertyChanged
实际INotifyPropertyChanged接口
View Code
下面是分别在mvc,wpf,winform下的使用实例
为了能在WPF上通用,所了也要继承属性更改通知接口INotifyPropertyChanged
实际INotifyPropertyChanged接口
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Reflection; namespace ClassLibrary1 { /// <summary> /// 验证类和更改通知类 /// System.ComponentModel.DataAnnotations; /// </summary> /// <typeparam name="T"></typeparam> public abstract class ValidationEntity<T> : NotifyPropertyChanged,IDataErrorInfo { public string Error { get { return null; } } public string this[string columnName] { get { return ValidateProperty(columnName); } } /// <summary> /// 验证是否通过 /// </summary> /// <param name="errors">错误信息 ErrorMessage 值提取</param> /// <returns></returns> public bool Valid(ref Dictionary<string, string> errors) { bool result = true; Type t = this.GetType(); PropertyInfo[] PropertyInfo = t.GetProperties(); try { foreach (PropertyInfo pi in PropertyInfo) { string name = pi.Name; if (name == "Error" || name=="Item") continue; object value1 = pi.GetValue(this, null); Dictionary<string, string> propertyErrors = new Dictionary<string, string>(); if (!IsPropertyValid(value1, name, ref propertyErrors)) { result = false; foreach (var item in propertyErrors) { if (!errors.ContainsKey(item.Key)) { errors.Add(item.Key, item.Value); } } } } } catch (Exception ex) { string aaaa = ex.Message; } return result; } /// <summary> /// 验证属性值是否合格 /// </summary> /// <param name="propertyName">属性名</param> /// <returns></returns> private string ValidateProperty(string propertyName) { if (string.IsNullOrEmpty(propertyName)) return string.Empty; object obj = this; var targetType = obj.GetType(); if (targetType != typeof(T)) { TypeDescriptor.AddProviderTransparent( new AssociatedMetadataTypeTypeDescriptionProvider(targetType, typeof(T)), targetType); } var propertyValue = targetType.GetProperty(propertyName).GetValue(obj, null); var validationContext = new ValidationContext(obj, null, null); validationContext.MemberName = propertyName; var validationResults = new List<ValidationResult>(); Validator.TryValidateProperty(propertyValue, validationContext, validationResults); if (validationResults.Count > 0) { return validationResults.First().ErrorMessage; } return string.Empty; } /// <summary> /// 验证属性值 /// </summary> /// <param name="propertyValue">属性值</param> /// <param name="propertyName">属性名</param> /// <param name="errors">错误信息</param> /// <returns></returns> private bool IsPropertyValid(object propertyValue, string propertyName, ref Dictionary<string, string> errors) { object obj = this; TypeDescriptor.AddProviderTransparent( new AssociatedMetadataTypeTypeDescriptionProvider(obj.GetType(), typeof(T)), obj.GetType()); var validationContext = new ValidationContext(obj, null, null); validationContext.MemberName = propertyName; var validationResults = new List<ValidationResult>(); Validator.TryValidateProperty(propertyValue, validationContext, validationResults); if (validationResults.Count > 0 && errors == null) errors = new Dictionary<string, string>(validationResults.Count); foreach (var validationResult in validationResults) { if (!errors.ContainsKey(validationResult.MemberNames.First())) errors.Add(validationResult.MemberNames.First(), validationResult.ErrorMessage); } if (validationResults.Count > 0) return false; else return true; } /// <summary> /// 辅助方法,把消息转成字符串 /// </summary> /// <param name="errors">消息</param> /// <returns></returns> public string ErrorToString(Dictionary<string, string> errors) { if (errors == null || errors.Count == 0) return ""; StringBuilder str = new StringBuilder(); foreach (var item in errors) { str.Append(item.Value); str.Append(Environment.NewLine); } str.Remove(str.Length - 1, 1); return str.ToString(); } } }
View Code
下面是分别在mvc,wpf,winform下的使用实例
相关文章推荐
- C# WPF vs WinForm
- ZedGraph:一个同时支持WinForm和WebForm的开源图表控件(基于LGPL协议,.NET 2.0 C#源代码)
- (转)C#多国语言支持的WinForm程序开发
- C# USB Detection - winform and WPF
- 清新空气---我的.net(C#)生涯知识总结 跨CSS,JS,JAVA,AJAX,WPF,WCF,LINQ,ASP.NET,Winform,Sqlserver,Mysql,EF,OOP,开发工具等
- C# 在winform或者wpf中显示控制台窗口
- 用c#创建支持多语言的WinForm应用程序
- C# Winform使用WPF控件
- WPF、WinForm(C#)多线程编程并更新界面(UI)
- C#用副线程改主线程(UI线程)的控件属性的方法(包括Winform和WPF)
- [C#]二维码生成、解码(QRCode)【支持winform、web调用】
- c# Winform/WPF 开发分屏显示应用程序
- 用c#创建支持多语言的WinForm应用程序
- C# 二维码生成、解码(QRCode)【支持winform、web调用】
- c# Winform/WPF 开发分屏显示应用程序
- C# Winform 支持Hex与ASCII输入和切换的文本框
- WPF、WinForm(C#)多线程编程并更新界面(UI)(转载积累)
- C#发送邮件小程序(支持群发,附件)winform
- C#如何开发多语言支持的Winform程序
- 【C#】wpf添加gif动图支持