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 小时前
Java面试基础:概念
java·开发语言·jvm
hackchen1 小时前
Go与JS无缝协作:Goja引擎实战之错误处理最佳实践
开发语言·javascript·golang
铲子Zzz3 小时前
Java使用接口AES进行加密+微信小程序接收解密
java·开发语言·微信小程序
小小小新人121233 小时前
C语言 ATM (4)
c语言·开发语言·算法
Two_brushes.3 小时前
【linux网络】网络编程全流程详解:从套接字基础到 UDP/TCP 通信实战
linux·开发语言·网络·tcp/udp
小白学大数据3 小时前
R语言爬虫实战:如何爬取分页链接并批量保存
开发语言·爬虫·信息可视化·r语言
争不过朝夕,又念着往昔3 小时前
Go语言反射机制详解
开发语言·后端·golang
Azxcc04 小时前
C++异步编程入门
开发语言·c++
Biaobiaone4 小时前
Java中的生产消费模型解析
java·开发语言
我命由我123454 小时前
前端开发问题:SyntaxError: “undefined“ is not valid JSON
开发语言·前端·javascript·vue.js·json·ecmascript·js