WPF点击提交按钮后验证

1.定义ValidateModelBase 基类,实现IDataErrorInfo接口来触发验证信息,

csharp 复制代码
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using CommunityToolkit.Mvvm.ComponentModel;
 
   /// <summary>
   /// 验证模型基类
   /// </summary>
   public class ValidateModelBase : ObservableObject, IDataErrorInfo
   {
       public ValidateModelBase()
       {
           DataErrors = new Dictionary<string, string>();
       }

       #region 属性

       /// <summary>
       /// 表当验证错误集合
       /// </summary>
       public Dictionary<string, string>? DataErrors { get; private set; } = new Dictionary<string, string>();

       /// <summary>
       /// 是否验证通过
       /// </summary>
       public bool IsValidated
       {
           get
           {
               return DataErrors?.Count == 0;
           }
       }

       //是否允许验证
       private bool _shouldValidate = false;

       #endregion 属性

       public string this[string columnName]
       {
           get
           {
               if (!_shouldValidate)
                   return string.Empty;

               if (columnName == null) throw new ArgumentNullException(nameof(columnName));

               ValidationContext vc = new ValidationContext(this, null, null)
               {
                   MemberName = columnName
               };

               var res = new List<System.ComponentModel.DataAnnotations.ValidationResult>();

               var propertyInfo = this.GetType().GetProperty(columnName);
               if (propertyInfo == null)
               {
                   return string.Empty;
               }

               var value = propertyInfo.GetValue(this, null);
               bool result = Validator.TryValidateProperty(value, vc, res);

               if (res.Count > 0)
               {
                   string errorInfo = string.Join(Environment.NewLine, res.Select(r => r.ErrorMessage).ToArray());
                   AddDic(DataErrors, columnName, errorInfo);
                   return errorInfo;
               }

               RemoveDic(DataErrors, columnName);
               return string.Empty;
           }
       }

       public string Error => string.Empty;

       #region 附属方法

       /// <summary>
       /// 移除字典
       /// </summary>
       private void RemoveDic(Dictionary<string, string>? dics, string dicKey)
       {
           if (dics != null)
           {
               dics.Remove(dicKey);
           }
       }

       /// <summary>
       /// 添加字典
       /// </summary>
       private void AddDic(Dictionary<string, string>? dics, string dicKey, string dicValue)
       {
           if (dics != null && !dics.ContainsKey(dicKey))
           {
               dics.Add(dicKey, dicValue);
           }
       }

       #endregion 附属方法

       /// <summary>
       /// 执行验证
       /// </summary>
       /// <returns></returns>
       public bool Validate()
       {
           _shouldValidate = true;
           this.GetType().GetProperties()
           .Where(prop => prop.GetCustomAttributes(false)
           .Any(attr => attr.GetType().Namespace == typeof(RequiredAttribute).Namespace))
           .ToList().ForEach(p => OnPropertyChanged(p.Name));
           //  this.GetType().GetProperties().ToList().ForEach(p => OnPropertyChanged(p.Name));
           return IsValidated;
       }
   }
相关推荐
程序员编程指南10 分钟前
Qt 开发自动化测试框架搭建
c语言·开发语言·c++·qt
三小尛21 分钟前
C++赋值运算符重载
开发语言·c++
籍籍川草24 分钟前
JVM指针压缩的那些事
java·开发语言·jvm
小徐不徐说32 分钟前
C++ 模板与 STL 基础入门:从泛型编程到实战工具集
开发语言·数据结构·c++·qt·面试
艾莉丝努力练剑33 分钟前
【C/C++】类和对象(上):(一)类和结构体,命名规范——两大规范,新的作用域——类域
java·c语言·开发语言·c++·学习·算法
froginwe111 小时前
WebPages PHP:深入解析PHP在网页开发中的应用
开发语言
R-G-B1 小时前
【33】C# WinForm入门到精通 ——表格布局器TableLayoutPanel【属性、方法、事件、实例、源码】
开发语言·c#·c# winform·表格布局器·tablelayoutpane
郝学胜-神的一滴2 小时前
Spring Boot Actuator 保姆级教程
java·开发语言·spring boot·后端·程序人生
赵英英俊2 小时前
Python day31
开发语言·python
freesheep7202 小时前
WPF使用PreviewTextInput事件限制用户输入
c#·wpf