June

4

12.5 数据的校验(组图)

 12.5 数据的校验 

  在双向绑定由目标到数据源更新数据的过程中,Silverlight支持对数据的校验。当遇到以下两种情况时,Silverlight将会报告数据验证错误。

  转换绑定数据时抛出异常。

  绑定数据源对象的set访问器抛出异常。

  为了获取这些数据验证错误信息,必须将绑定对象的ValidatesOnExceptions属性和NotifyOnValidationError属性设为True。

  将ValidatesOnExceptions属性设为True可以让绑定引擎在异常抛出时产生一个验证错误信息。将NotifyOnValidationError属性设为true可以通知绑定引擎当遇到验证错误时,触发BindingValidationError事件。

  对于BindingValidationError事件,可以为目标对象或者其父节点创建一个事件响应函数,来捕获该事件,从而对数据绑定出现异常的情况做出应对。

  BindingValidationError事件是一个路由事件,因此,不必让真正产生异常的那个对象处理BindingValidationError事件。BindingValidationError事件触发后将会向上冒泡传递,直至它被处理,所以可以在父节点上添加事件响应函数。

  下面的实例中,给从视图中绑定的歌曲长度属性添加了数据校验,并给BindingValidationError事件添加了响应函数,当产生验证错误信息时,将TextBox控件的背景色设为红色,直到数据验证错误去除后,将TextBox的背景色重新设为白色。具体操作步骤如下。

  (1)将从视图中显示歌曲长度属性的TextBlock控件改为TextBox控件,并将其绑定模式设置为双向绑定。同时将其ValidatesOnExceptions属性和NotifyOnValidationError属性设为True。如下面的代码所示。

  <TextBox x:Name=”length_tb” Width=”100″Text=”BindingLength,Mode=TwoWay, Converter=StaticResourcetimeSpanConverter,NotifyOnValidationError=true,ValidatesOnExceptions=true”Canvas.center=”200″Canvas.Top=”150″FontFamily=”SimHei” FontSize=”22″/>

  (2)然后打开TimeSpanConverter.cs文件,实现ConvertBack函数,使其将输入的字符串格式数据转换成TimeSpan类型的数据。代码如下所示。

  public t ConvertBack(t value, Type targetType,t meter,CultureInfoculture)TimeSpan length = TimeSpan.Parse(”0:”+(string)value);return length;

  (3)在MusicDetail类中给BindingValidationError事件添加事件响应函数,如例程12-17所示。

  例程12-17 给BindingValidationError事件添加事件响应函数

  using System;usingSystem.Collections.Generic;usingSystem.Linq;using System.Net;usingSystem.Windows;usingSystem.Windows.Controls;usingSystem.Windows.Documents;usingSystem.Windows.Input;usingSystem.Windows.Media;usingSystem.Windows.Media.Animation;usingSystem.Windows.Shapes;

  namespace BindingCollectionSamplepublic partial classMusicDetail:UserControlpublicMusicDetail()InitializeComponent();this.BindingValidationError+=newEventHandler<ValidationErrorEventArgs>(this_BindingValidationError);

  void this_BindingValidationError(tsender,ValidationErrorEventArgse)if(e.ActionValidationErrorEventAction.Added)this.length_tb.Background= newSolidColorBrush(Colors.Red);else if(e.ActionValidationErrorEventAction.Removed)this.length_tb.Background= newSolidColorBrush(Colors.White);

  (4)构造一个数据验证条件,这里在Music类的set访问器中添加下面的代码,使得当歌曲长度小于1秒时抛出异常,从而产生数据验证错误信息。

  private TimeSpan length;public TimeSpan Lengthget returnlength;setif (value < new TimeSpan(0, 0, 1))thrownewException(”歌曲长度必须大于1秒”);

  length = value;NotifyPropertyChanged(”Length”);

  运行后的效果如图12-15所示,选中歌曲《夜曲》后,在文本框中将歌曲长度设为”0:00″,由于设置的歌曲长度小于1秒,将会产生数据验证错误,使文本框的背景色变成了红色。

 

图12-15 数据验证未

  通过时给予提示 

  当把歌曲长度设为”2:45″时,就可以通过数据验证,从而使文本框背景色又变回到白色,如图12-16所示。

 

图12-16 数据验证通

  过时恢复正常

RSS Feed

No comments yet.

Leave a comment

Anti-spam text: (Required) *
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text. Click to hear an audio file of the anti-spam word

« Visual Studio 2010 Beta 1安装和调试 | 12.3.3 实现主从关系视图 »