SuperAPI AI 工具集

implementing-wpf-validation

数据与分析

查看项目

更新于 10-15 20:12

技能介绍

用途:在 WPF 应用中实现数据验证,覆盖表单输入校验与错误展示。

主要能力:资料对比了多种验证方式。ValidationRule 写在 XAML 绑定中,声明式、简单,但难以与 ViewModel 分离;IDataErrorInfo 位于 ViewModel,集成方便,仅支持同步验证;INotifyDataErrorInfo 支持异步与多错误,实现较复杂,被推荐使用;ExceptionValidationRule 基于异常,可能有性能影响。

使用方式:自定义 ValidationRule 需重写 Validate 返回 ValidationResult,并在 Binding.ValidationRules 中引用,可配合 Validation.ErrorTemplate 与 Validation.HasError 触发器显示错误。IDataErrorInfo 通过索引器按属性名返回错误消息,绑定需设置 ValidatesOnDataErrors=True。INotifyDataErrorInfo 需实现 HasErrors、GetErrors、ErrorsChanged,并提供 AddError、ClearErrors 等方法,绑定设置 ValidatesOnNotifyDataErrors=True。CommunityToolkit.Mvvm 8.0+ 的 ObservableValidator 可结合 Required、MinLength、Range、EmailAddress 等 DataAnnotations 特性,在属性变更时调用 ValidateProperty,提交时调用 ValidateAllProperties。

适用场景:简单 XAML 校验、ViewModel 校验、DataAnnotations、异步验证、旧版兼容、复杂业务规则(可参考 FluentValidation 技能)以及服务层错误(可参考 ErrorOr 技能)。

限制:资料未提供具体安装命令、版本要求、性能数据或平台限制;部分实现依赖 CommunityToolkit.Mvvm 与 GeneratedRegex 等特性。