设置Binding的ValidationRules属性对Binding进行检验
2 |
< TextBox x:Name = "txtAge" FontSize = "30" Foreground = "Red" ></ TextBox > |
3 |
< TextBlock x:Name = "errorSummary" FontSize = "30" Foreground = "Red" ></ TextBlock > |
后台代码
01 |
public partial class MainWindow : Window |
06 |
InitializeComponent(); |
07 |
Person p = new Person { Age = 20, Name = "Tom" }; |
08 |
Binding binding = new Binding( "Age" ) { Source = p }; |
10 |
binding.NotifyOnValidationError = true ; |
12 |
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; |
13 |
RangeValidationRule rv = new RangeValidationRule(); |
14 |
binding.ValidationRules.Add(rv); |
15 |
this .txtAge.SetBinding(TextBox.TextProperty, binding); |
17 |
this .txtAge.AddHandler(Validation.ErrorEvent, new RoutedEventHandler( this .ValidationError)); |
20 |
void ValidationError( object sender, RoutedEventArgs e) |
22 |
if (Validation.GetErrors( this .txtAge).Count > 0) |
24 |
this .txtAge.ToolTip = Validation.GetErrors( this .txtAge)[0].ErrorContent.ToString(); |
25 |
this .errorSummary.Text = Validation.GetErrors( this .txtAge)[0].ErrorContent.ToString(); |
同样,我们在XAML里也可以设置验证
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 > |
09 |
< TextBlock x:Name = "errorSummary" FontSize = "30" Foreground = "Red" ></ TextBlock > |
后台代码:
01 |
public partial class MainWindow : Window |
05 |
InitializeComponent(); |
06 |
Person p = new Person { Age = 20, Name = "Tom" }; |
09 |
private void txtAge_Error( object sender, ValidationErrorEventArgs e) |
11 |
if (Validation.GetErrors( this .txtAge).Count > 0) |
13 |
this .txtAge.ToolTip = Validation.GetErrors( this .txtAge)[0].ErrorContent.ToString(); |
15 |
this .errorSummary.Text = Validation.GetErrors( this .txtAge)[0].ErrorContent.ToString(); |