博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

WPF-Binding对数据的检验

Posted on 2011-05-06 23:00  linFen  阅读(1194)  评论(0编辑  收藏  举报

设置Binding的ValidationRules属性对Binding进行检验

1 <StackPanel>
2        <TextBox x:Name="txtAge" FontSize="30" Foreground="Red"></TextBox>
3        <TextBlock x:Name="errorSummary" FontSize="30" Foreground="Red"></TextBlock>
1 </StackPanel>

 

后台代码

01 public partial class MainWindow : Window
02     {
03           
04         public MainWindow()
05         {
06             InitializeComponent();
07             Person p = new Person { Age = 20, Name = "Tom" };
08             Binding binding = new Binding("Age") { Source = p };
09   
10             binding.NotifyOnValidationError = true;
11   
12             binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
13             RangeValidationRule rv = new RangeValidationRule();
14             binding.ValidationRules.Add(rv);
15             this.txtAge.SetBinding(TextBox.TextProperty, binding);
16   
17             this.txtAge.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(this.ValidationError));
18         }
19   
20         void ValidationError(object sender, RoutedEventArgs e)
21         {
22             if (Validation.GetErrors(this.txtAge).Count > 0)
23             {
24                 this.txtAge.ToolTip = Validation.GetErrors(this.txtAge)[0].ErrorContent.ToString();
25                 this.errorSummary.Text = Validation.GetErrors(this.txtAge)[0].ErrorContent.ToString();
1                 // You can do everything here when validation error occurs
2             }
3         }
4           
5     }
6 }

 

image

 

同样,我们在XAML里也可以设置验证

01 <StackPanel>
02         <TextBox x:Name="txtAge" FontSize="30" Foreground="Red"   Validation.Error="txtAge_Error">
03             <Binding NotifyOnValidationError="True" Path="Age" UpdateSourceTrigger="PropertyChanged">
04                 <Binding.ValidationRules>
05                     <local:RangeValidationRule></local:RangeValidationRule>
06                 </Binding.ValidationRules>
07             </Binding>
08         </TextBox>
09         <TextBlock x:Name="errorSummary" FontSize="30" Foreground="Red"></TextBlock>
10 </StackPanel>

 

后台代码:

01 public partial class MainWindow : Window
02     {        
03         public MainWindow()
04         {
05             InitializeComponent();
06             Person p = new Person { Age = 20, Name = "Tom" };
07             this.DataContext = p;           
08         }        
09         private void txtAge_Error(object sender, ValidationErrorEventArgs e)
10         {
11             if (Validation.GetErrors(this.txtAge).Count > 0)
12             {
13                 this.txtAge.ToolTip = Validation.GetErrors(this.txtAge)[0].ErrorContent.ToString();
14   
15                 this.errorSummary.Text = Validation.GetErrors(this.txtAge)[0].ErrorContent.ToString();
16                 // You can do everything here when validation error occurs
17             }
18         }        
19 }