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;
       }
   }
相关推荐
benchmark_cc4 小时前
量化项目启动时,应该先设计数据接口还是先编写策略?从系统架构角度做出正确选择
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
2601_962885724 小时前
如何用 Python 判断一只股票“追涨”还是“抄底”更有效?
android·开发语言·python
denlaku5 小时前
JDK 15 新特性详解
java·开发语言
滴滴答答哒5 小时前
C# 技巧:优雅实现对象的“局部更新”与“字段合并”
开发语言·c#
灯澜忆梦5 小时前
【面向对象编程c++】| 指针与自定义数据类型
开发语言·c++·算法
Brilliantwxx5 小时前
【Linux】 自主shell编写巩固复习篇
linux·运维·服务器·开发语言
十年Java程序媛5 小时前
Java 多线程基础与锁机制详解|进程线程、锁升级、synchronized 与 Lock 对比
java·开发语言·spring boot
弯_弯5 小时前
FDE 的工程能力画像:数据接入、PoC 与可复用资产的落地口径
java·服务器·开发语言
雾沉川6 小时前
Visual C++运行库合集 v105.0 安装教程
开发语言·c++·dll
niucloud-admin6 小时前
NIUCLOUD LITE AI开发文档—模块开发:支付管理
开发语言