深入浅出WPF 第二部分(10)
6.4 Binding对数据的转换与校验
Binding用于数据有效性校验的关卡是它的ValidationRules属性,用于数据类型转换的关卡是它的Converter属性。
6.4.1 Binding的数据校验
ValidationRule类是个抽象类,在使用的时候我们需要创建他的派生类并实现它的Validate方法。Validate方法的返回值是ValidationRule类型对象,如果校验通过,就把validationResult对象的IsValid属性设为True。反之,需要把IsValid属性设为false并为其ErrorContent属性设置一个合适的消息内容(一般是个字符串)。
public MainWindow() { InitializeComponent(); var source=new Binding("Value") { ElementName = "slider1", UpdateSourceTrigger=UpdateSourceTrigger.PropertyChanged }; var rar = new RangeValidationRule(); rar.ValidatesOnTargetUpdated = true; //1# source.ValidationRules.Add(rar); source.NotifyOnValidationError = true; //2# textBox1.SetBinding(TextBox.TextProperty, source); //5#路由事件 this.textBox1.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(this.ValidationError)); //3# 加载路由委托 } void ValidationError(object sender, RoutedEventArgs e) { foreach (var error in Validation.GetErrors(this.textBox1)) //4# this.textBox1.ToolTip = error.ErrorContent.ToString(); } }