WPF 验证之Attribute
效果

还是准备一个ViewModel 在要验证的属性上面添加验证特性
1 public class ViewModel 2 { 3 private int _age; 4 5 private string _eMail; 6 7 private string _name; 8 9 [Range(0, 120, ErrorMessage = "年龄范围[0-120]")] 10 public int Age 11 { 12 get => _age; 13 set { _age = value; ValidateProperty(value); } 14 } 15 16 [EmailAddress(ErrorMessage = "邮箱地址不正确")] 17 public string Email 18 { 19 get { return _eMail; } 20 set { _eMail = value; ValidateProperty(value); } 21 } 22 23 [Required(ErrorMessage = "姓名不能为空")] 24 [StringLength(12, MinimumLength = 4, ErrorMessage = "姓名长度[4-12]")] 25 public string Name 26 { 27 get => _name; 28 set { _name = value; ValidateProperty(value); } 29 } 30 31 /// <summary> 32 /// 验证属性 33 /// </summary> 34 /// <typeparam name="T"></typeparam> 35 /// <param name="value"></param> 36 /// <param name="propertyName"></param> 37 protected void ValidateProperty<T>(T value, [CallerMemberName] string propertyName = "") 38 { 39 var contex = new ValidationContext(this) { MemberName = propertyName }; 40 Validator.ValidateProperty(value, contex);//此处不好调试,要进入到异常,不知为何,有大佬指教吗? 41 } 42 }
前台界面
关键是
ValidatesOnExceptions=True 这句代码,开启异常验证
1 <Window.Resources> 2 <ControlTemplate x:Key="TextBoxErrorTemplate"> 3 <StackPanel Orientation="Horizontal"> 4 <AdornedElementPlaceholder x:Name="Adorner" /> 5 <TextBlock 6 Margin="10,0,0,0" 7 Foreground="Red" 8 Text="{Binding ElementName=Adorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" /> 9 </StackPanel> 10 </ControlTemplate> 11 </Window.Resources> 12 <Window.DataContext> 13 <local:ViewModel /> 14 </Window.DataContext> 15 <Grid> 16 <StackPanel 17 Width="300" 18 HorizontalAlignment="Center" 19 VerticalAlignment="Center" 20 Orientation="Vertical"> 21 <StackPanel Orientation="Horizontal"> 22 <TextBlock Text="姓名:" /> 23 <TextBox 24 Width="220" 25 Margin="5" 26 Text="{Binding Path=Name, ValidatesOnExceptions=True}" 27 Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}" /> 28 </StackPanel> 29 <StackPanel Orientation="Horizontal"> 30 <TextBlock Text="年龄:" /> 31 <TextBox 32 Width="220" 33 Margin="5" 34 Text="{Binding Path=Age, ValidatesOnExceptions=True}" 35 Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}" /> 36 </StackPanel> 37 <StackPanel Orientation="Horizontal"> 38 <TextBlock Text="邮箱:" /> 39 <TextBox 40 Width="220" 41 Margin="5" 42 Text="{Binding Path=Email, ValidatesOnExceptions=True}" 43 Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}" /> 44 </StackPanel> 45 </StackPanel> 46 </Grid>
可以看到,这种方法相对于IDataErrorInfo方便了很多 可以和ValidationRule配合使用

浙公网安备 33010602011771号