本文介绍的是DataAnnotation验证机制,利用RIA service提供的验证机制,
需要引入名称空间:
using System.ComponentModel.DataAnnotations;
本文以填写用户名和密码为例简单说明必填验证的方法.
验证类如下:
1 private string _userName;
2 [Required(ErrorMessage = "必填选项")]
3 public string UserName
4 {
5 get { return _userName; }
6 set
7 {
8 if (_userName!=value)
9 {
10 //_userName = value;
11 //NotifyPropertyChanged("UserName");
12
13 var tmpValidator = new ValidationContext(this, null, null);
14 tmpValidator.MemberName = "UserName";
15 Validator.ValidateProperty(value, tmpValidator);
16 _userName = value;
17
18 }
1920
21 }
22 }
2 [Required(ErrorMessage = "必填选项")]
3 public string UserName
4 {
5 get { return _userName; }
6 set
7 {
8 if (_userName!=value)
9 {
10 //_userName = value;
11 //NotifyPropertyChanged("UserName");
12
13 var tmpValidator = new ValidationContext(this, null, null);
14 tmpValidator.MemberName = "UserName";
15 Validator.ValidateProperty(value, tmpValidator);
16 _userName = value;
17
18 }
1920
21 }
22 }
客户端设置如下:
第一步引入:
xmlns:local="clr-namespace:SilverlightApplication2"
第二步
<local:User x:Key="userDataContext"/>
第三步绑定数据源
1 <TextBox Grid.Column="1" Height="30" HorizontalAlignment="Left" Margin="28,57,0,0" Name="textBox1" DataContext="{Binding Source={StaticResource userDataContext}}" Text="{Binding UserName,Mode=TwoWay,NotifyOnValidationError=True,ValidatesOnExceptions=True}" VerticalAlignment="Top" Width="158" />
2 <TextBox Height="30" HorizontalAlignment="Left" Margin="28,55,0,0" Name="textBox2" DataContext="{Binding Source={StaticResource userDataContext}}" Text="{Binding Password,Mode=TwoWay,NotifyOnValidationError=True,ValidatesOnExceptions=True}" VerticalAlignment="Top" Width="158" Grid.Column="1" Grid.Row="1" />
2 <TextBox Height="30" HorizontalAlignment="Left" Margin="28,55,0,0" Name="textBox2" DataContext="{Binding Source={StaticResource userDataContext}}" Text="{Binding Password,Mode=TwoWay,NotifyOnValidationError=True,ValidatesOnExceptions=True}" VerticalAlignment="Top" Width="158" Grid.Column="1" Grid.Row="1" />
第四步,捕获
1 private void LayoutRoot_BindingValidationError(object sender, ValidationErrorEventArgs e)
2 {
3 if (e.Action == ValidationErrorEventAction.Added)
4 {
5 (e.OriginalSource as Control).Background = new SolidColorBrush(Colors.Yellow);
6 tbMessage.Text = e.Error.Exception.Message;
7 }
8
9 if (e.Action == ValidationErrorEventAction.Removed)
10 {
11 (e.OriginalSource as Control).Background = new SolidColorBrush(Colors.White);
12 tbMessage.Text = "";
13 }
14 }
2 {
3 if (e.Action == ValidationErrorEventAction.Added)
4 {
5 (e.OriginalSource as Control).Background = new SolidColorBrush(Colors.Yellow);
6 tbMessage.Text = e.Error.Exception.Message;
7 }
8
9 if (e.Action == ValidationErrorEventAction.Removed)
10 {
11 (e.OriginalSource as Control).Background = new SolidColorBrush(Colors.White);
12 tbMessage.Text = "";
13 }
14 }
效果如下: