效果
首先准备一个ViewModel类 实现IDataErrorInfo接口
1 public class ViewModel : INotifyPropertyChanged, IDataErrorInfo 2 { 3 private string _error; 4 5 public int Age { get; set; } 6 7 public string Error 8 { 9 get { return _error; } 10 set { _error = value; OnPropertyChanged(); } 11 } 12 13 public string Name { get; set; } 14 15 public event PropertyChangedEventHandler PropertyChanged; 16 17 public void OnPropertyChanged([CallerMemberName] string propertyName = "") 18 { 19 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 20 } 21 22 /// <summary> 23 /// 索引器验证属性 24 /// </summary> 25 /// <param name="columnName"></param> 26 /// <returns></returns> 27 public string this[string columnName] 28 { 29 get 30 { 31 switch (columnName) 32 { 33 case nameof(Name): 34 if (string.IsNullOrWhiteSpace(Name)) 35 { 36 return "姓名不能为空"; 37 } 38 else 39 { 40 if (Name.Length < 4) 41 { 42 return "姓名长度不能<4"; 43 } 44 else if (Name.Length > 12) 45 { 46 return "姓名长度不能>12"; 47 } 48 } 49 return ""; 50 51 case nameof(Age): 52 if (Age < 0) 53 { 54 return "年龄不能<0"; 55 } 56 else if (Age > 120) 57 { 58 return "年龄不能>120"; 59 } 60 return ""; 61 62 default: 63 return ""; 64 } 65 } 66 } 67 }
界面代码
Text 属性绑定中( ValidatesOnDataErrors=True )这个是关键 开启验证的入口
1 <Grid> 2 <StackPanel 3 Width="300" 4 HorizontalAlignment="Center" 5 VerticalAlignment="Center" 6 Orientation="Vertical"> 7 <StackPanel Orientation="Horizontal"> 8 <TextBlock Text="姓名:" /> 9 <TextBox 10 Width="220" 11 Margin="5" 12 Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" 13 ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" /> 14 </StackPanel> 15 <StackPanel Orientation="Horizontal"> 16 <TextBlock Text="年龄:" /> 17 <TextBox 18 Width="220" 19 Margin="5" 20 Text="{Binding Path=Age, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" 21 ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" /> 22 </StackPanel> 23 </StackPanel> 24 </Grid>
可以看到 IDataInfo里面验证属性要写很啰嗦的代码 而且无法复用,不怎么方便!