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;
       }
   }
相关推荐
GokuCode13 小时前
【GO高级编程】02.GO接收者概述
开发语言·后端·golang
Aotman_13 小时前
JavaScript去除对象字段空格
开发语言·前端·javascript
云和数据.ChenGuang14 小时前
Zabbix 6 与 PHP 5 版本**完全不兼容
运维·开发语言·php·zabbix·运维工程师
csbysj202014 小时前
Ruby 范围(Range)
开发语言
苏 凉14 小时前
在 openEuler 24.03 LTS SP2 上安装部署 iSula 容器引擎及性能测试
开发语言·rust
qq_3363139314 小时前
HashMap
java·开发语言
专注VB编程开发20年14 小时前
C# int*指向 int 的指针类型(unsafe 上下文)
java·开发语言·c#
要站在顶端14 小时前
iOS自动化测试全流程教程(基于WebDriverAgent+go-ios)
开发语言·ios·golang
liwulin050614 小时前
【PYTHON】python venv创建虚拟环境,非conda
开发语言·python·conda
fengfuyao98514 小时前
基于MATLAB的支持向量机在故障诊断中的应用例程
开发语言·支持向量机·matlab