一.说明
本文使用FluentValidation对实体对象中属性进行校验,并在Xaml中使用MaterialDesign固有样式和自定义样式展示不同的效果。FluentValidation安装包可以通过nuget包自行下载。
二.后台校验代码
Student:需要校验的实体对象;
Model:实现INotifyPropertyChanged的一个抽象对象;
IDataErrorInfo:用于校验的接口,使用FluentValidation(StudentValidator)对其进行实现。
StudentValidator:基于AbstractValidator<泛型> 实现对该类型对象属性的校验。
public class StudentValidator:AbstractValidator<Student>
{
public StudentValidator()
{
RuleFor(x => x.Name).NotEmpty().WithMessage("Please specify a name");
RuleFor(x => x.Age).InclusiveBetween(1, 100);
}
}
public class Student:Model, IDataErrorInfo
{
private string _name;
private int _age;
private bool _sex;
public string Name
{
get => _name;
set =>SetProperty(ref _name, value);
}
public int Age
{
get=> _age;
set => SetProperty(ref _age, value);
}
public bool Sex
{
get => _sex;
set => SetProperty(ref _sex, value);
}
public string this[string columnName]
{
get
{
if (validator is null) validator = new StudentValidator();
var first = validator.Validate(this)
.Errors.FirstOrDefault(o => o.PropertyName == columnName);
return first?.ErrorMessage;
}
}
public string Error { get; }
private StudentValidator validator;
}
三.前台Xmal代码
这里注意下,因为我这里引入了MaterialDesign, Name对应的样式默认使用的是MD中的样式。Age做了修改使用自定义样式,最后看效果图。
<ListView ItemsSource="{Binding StudentsSource}" Grid.Row="1">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBox Text="{Binding Name,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}" />
<TextBox Text="{Binding Age,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}" Style="{StaticResource ErrorStyle}"/>
<TextBox Text="{Binding Sex,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
自定义样式ErrorStyle
<Style TargetType="{x:Type TextBox}" x:Key="ErrorStyle">
<Setter Property="Width" Value="200"/>
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel>
<Grid DockPanel.Dock="Right" Width="16" Height="16"
VerticalAlignment="Center" Margin="3 0 0 0">
<Ellipse Width="16" Height="16" Fill="Red"/>
<Ellipse Width="3" Height="8"
VerticalAlignment="Top" HorizontalAlignment="Center"
Margin="0 2 0 0" Fill="White"/>
<Ellipse Width="2" Height="2" VerticalAlignment="Bottom"
HorizontalAlignment="Center" Margin="0 0 0 2"
Fill="White"/>
</Grid>
<Border BorderBrush="Red" BorderThickness="2" CornerRadius="2">
<AdornedElementPlaceholder/>
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource=
{x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
四.效果图
这里的Name 和 Age是两种不同的Style,Name错误描述(Please specify a name)就是我们在后台利FluentValidation过滤出来的。
关于FluentValidation功能很强大,感兴趣可以去Github上学习下FluentValidation。
最后感谢各位大佬支持关注。