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;
       }
   }
相关推荐
秦禹辰1 小时前
本地Docker部署开源Web相册图库Piwigo与在线远程访问实战方案
开发语言·后端·golang
the beard1 小时前
深入理解Java多线程:状态、安全、同步与通信
java·开发语言
lucky_lyovo2 小时前
大模型部署
开发语言·人工智能·云计算·lua
Warren983 小时前
如何在 Spring Boot 中安全读取账号密码等
java·开发语言·spring boot·后端·安全·面试·测试用例
燃尽了,可无4 小时前
C#基础编程核心知识点总结
开发语言·c#
界面开发小八哥4 小时前
图表组件SciChart WPF再升级:v8.9带来油气井图、新交互与可视化增强
信息可视化·wpf·数据可视化·scichart
llrraa20105 小时前
python whisper生成字幕
开发语言·python·whisper
努力努力再努力wz5 小时前
【c++进阶系列】:万字详解多态
java·linux·运维·开发语言·c++
秦亿凡5 小时前
多线程下为什么用ConcurrentHashMap而不是HashMap
java·开发语言
阿波罗尼亚5 小时前
ExcelUtils实现 设置内容 插入行 复制行列格式
java·开发语言