绑定数据中加入校验

一、什么是绑定校验?

一句话定义:
在数据从界面写回数据源的过程中,自动检查输入是否合法,不合法就提示错误。
常见场景:
  • 输入框不能为空
  • 年龄必须是 1-100 之间的数字
  • 密码长度不能小于 6 位
  • 邮箱格式必须正确

二、WPF 提供的 2 种校验方式

1. 异常验证(最简单,推荐新手)

后台属性 set 方法里抛异常,界面自动捕获并提示。

2. 验证规则(ValidationRule)

纯 XAML 或独立类编写校验规则,不污染业务代码(更规范)。

三、必备前提

要让校验生效,绑定必须开启校验:
1 ValidatesOnDataErrors="True" 
2 ValidatesOnExceptions="True"
3 NotifyOnValidationError="True"

四、方式 1:异常验证(最简单,5 分钟学会)

步骤 1:后台属性里做判断,抛异常

public class Student : INotifyPropertyChanged
{
    private int _age;

    public int Age
    {
        get => _age;
        set
        {
            // 校验逻辑
            if (value < 1 || value > 100)
            {
                // 抛异常,WPF 自动捕获
                throw new ArgumentOutOfRangeException("年龄必须在 1-100 之间!");
            }

            _age = value;
            OnPropertyChanged();
        }
    }

    // ... 接口实现代码不变 ...
}

步骤 2:界面绑定开启校验

<TextBox 
    Text="{Binding Age, 
            Mode=TwoWay, 
            ValidatesOnExceptions=True,  <!-- 开启异常验证 -->
            UpdateSourceTrigger=PropertyChanged}"  <!-- 输入时实时校验 -->
    FontSize="20"
    Width="200"/>

效果

  • 输入 0 → 自动出现红色边框
  • 输入 101 → 自动报错
  • 输入 18 → 正常

五、方式 2:独立验证规则(ValidationRule,企业级推荐)

这种方式不修改后台代码,校验逻辑独立,更干净。

步骤 1:创建校验规则类

继承 ValidationRule
 1 public class AgeValidationRule : ValidationRule
 2 {
 3     // 核心方法:校验逻辑
 4     public override ValidationResult Validate(object value, CultureInfo cultureInfo)
 5     {
 6         // 判断是否为空
 7         if (string.IsNullOrEmpty(value?.ToString()))
 8         {
 9             return new ValidationResult(false, "年龄不能为空!");
10         }
11 
12         // 判断是否是数字
13         if (!int.TryParse(value.ToString(), out int age))
14         {
15             return new ValidationResult(false, "必须输入数字!");
16         }
17 
18         // 判断范围
19         if (age < 1 || age > 100)
20         {
21             return new ValidationResult(false, "年龄必须在 1-100 之间!");
22         }
23 
24         // 验证通过
25         return ValidationResult.ValidResult;
26     }
27 }

步骤 2:在 XAML 绑定中加入规则

 1 <TextBox FontSize="20" Width="200">
 2     <TextBox.Text>
 3         <Binding Path="Age" Mode="TwoWay" UpdateSourceTrigger=PropertyChanged>
 4             <Binding.ValidationRules>
 5                 <!-- 加入我们的校验规则 -->
 6                 <local:AgeValidationRule/>
 7             </Binding.ValidationRules>
 8         </Binding>
 9     </TextBox.Text>
10 </TextBox>

效果

  • 空 → 报错
  • 字母 → 报错
  • 101 → 报错
  • 18 → 正常

六、方式 3:IDataErrorInfo(最常用、最强大)

MVVM 标准验证方式,一个类统一管理所有验证。

步骤 1:类继承 IDataErrorInfo

 1 public class Student : INotifyPropertyChanged, IDataErrorInfo
 2 {
 3     public string Name { get; set; }
 4     public int Age { get; set; }
 5 
 6     // 索引器:根据属性名做校验
 7     public string this[string columnName]
 8     {
 9         get
10         {
11             string error = string.Empty;
12 
13             switch (columnName)
14             {
15                 case nameof(Age):
16                     if (Age < 1 || Age > 100)
17                         error = "年龄必须在1-100之间";
18                     break;
19 
20                 case nameof(Name):
21                     if (string.IsNullOrWhiteSpace(Name))
22                         error = "姓名不能为空";
23                     break;
24             }
25             return error;
26         }
27     }
28 
29     public string Error => string.Empty;
30 }

步骤 2:绑定开启 IDataErrorInfo 校验

1 <TextBox 
2     Text="{Binding Age, 
3             ValidatesOnDataErrors=True,  <!-- 开启 -->
4             NotifyOnValidationError=True,
5             UpdateSourceTrigger=PropertyChanged}" />

效果

自动校验,自动红色提示。

七、显示错误提示信息(不只是红框,还要文字)

默认只有红框,我们可以显示错误文字:
 1 <StackPanel>
 2     <TextBox x:Name="txtAge" Width="200" FontSize="20">
 3         <!-- 绑定+校验代码 -->
 4     </TextBox>
 5 
 6     <!-- 显示错误信息 -->
 7     <TextBlock 
 8         Foreground="Red" 
 9         Text="{Binding ElementName=txtAge, Path=(Validation.Errors)[0].ErrorContent}"
10         Visibility="{Binding ElementName=txtAge, Path=(Validation.HasError), Converter={x:Static local:BoolToVisibilityConverter.Instance}}"/>
11 </StackPanel>

八、3 种方式对比(新手必看)

方式难度优点适用场景
异常验证 🌟 最简单 小项目、快速开发
ValidationRule 🌟🌟 独立、干净 复用校验规则
IDataErrorInfo 🌟🌟🌟 MVVM 标准、强大 企业级、正式项目
 
 
九、绑定校验必加的 3 个属性
1 ValidatesOnExceptions="True"       <!-- 捕获异常 -->
2 ValidatesOnDataErrors="True"       <!-- 捕获 IDataErrorInfo -->
3 NotifyOnValidationError="True"     <!-- 触发错误通知 -->
4 UpdateSourceTrigger="PropertyChanged"  <!-- 实时校验 -->

十、完整模板(复制即用)

1. 校验规则类

1 public class MyRule : ValidationRule
2 {
3     public override ValidationResult Validate(object value, CultureInfo cultureInfo)
4     {
5         // 你的校验逻辑
6         return ValidationResult.ValidResult;
7     }
8 }

2. XAML 绑定

1 <TextBox>
2     <TextBox.Text>
3         <Binding Path="xxx" UpdateSourceTrigger=PropertyChanged>
4             <Binding.ValidationRules>
5                 <local:MyRule/>
6             </Binding.ValidationRules>
7         </Binding>
8     </TextBox.Text>
9 </TextBox>

十一、核心总结(1 分钟记住)

  1. WPF 自带校验,不用自己写弹窗、判断
  2. 3 种方式:异常、ValidationRule、IDataErrorInfo
  3. 绑定必须开启:ValidatesOnExceptions、ValidatesOnDataErrors
  4. 实时校验:UpdateSourceTrigger=PropertyChanged
  5. 错误显示:红色边框 + 错误文字提示
posted on 2026-03-26 17:35  工业搬砖猿Lee  阅读(33)  评论(0)    收藏  举报