Binding数据校验、并捕获异常信息的三种方式
WPF在使用Binding时,经常需要进行数据校验,如果校验失败需要捕获失败的原因,并加以展示,本文主要介绍数据校验异常并捕获的三种方式。
依赖属性异常捕获
- 先定义一个依赖属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public int Value { get { return (int)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } }
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(int), typeof(MainWindow), new PropertyMetadata(0), new ValidateValueCallback(OnValueValidation));
private static bool OnValueValidation(object value) { if (value.ToString() == "123") return false;
return true; }
|
- 想要获得错误内容,需要用
Validation.Errors
静态函数,获得一个集合,一般都是一条数据。 - XAML代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <TextBox x:Name="tb"> <TextBox.Text> <Binding Path="Value" RelativeSource="{RelativeSource AncestorType=Window}" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <ExceptionValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox>
<TextBlock Text="{Binding Path=(Validation.Errors)[0].ErrorContent, ElementName=tb}" />
|

属性抛出Exception异常捕获
如果不是依赖属性,可以利用引发异常的方式来让XAML来捕获。
类中的某个普通属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class MyData { private string _value = "200";
public string Value { get { return _value; } set { _value = value;
if (value == "123") throw new System.Exception("报错了~~~[Exception]"); } } }
|
在XAML中增加DataContext
1 2 3
| <Window.DataContext> <local:MyData /> </Window.DataContext>
|
- XAML界面代码
1 2 3 4 5 6 7 8 9 10
| <TextBox x:Name="tb1"> <TextBox.Text> <Binding Path="Value" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <ExceptionValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> <TextBlock Text="{Binding Path=(Validation.Errors)[0].ErrorContent, ElementName=tb1}" />
|
此时在文本框中输入123,会直接引发异常

点击继续调试,会出现如下效果,调试状态下会比较难受,但是在程序打包运行后,效果和之前一样,但是不推荐这样,比较消耗资源。

使用ValidationRule异常捕获
可以自定一个类,继承自ValidationRule
,类中包括验证规则
- 新建规则类
1 2 3 4 5 6 7 8 9
| public class ValueValidtionRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { if (value.ToString() == "123") return new ValidationResult(false, "报错了~~~~[ValueValidtionRule]"); return new ValidationResult(true, ""); } }
|
- XAML中
1 2 3 4 5 6 7 8 9 10 11 12 13
| <TextBox x:Name="tb2"> <TextBox.Text> <Binding Path="Value" RelativeSource="{RelativeSource AncestorType=Window}" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <local:ValueValidtionRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> <TextBlock Text="{Binding Path=(Validation.Errors)[0].ErrorContent, ElementName=tb2}" />
|
