WPF下使用FluentValidation校验

本文介绍了如何在C#中利用FluentValidation对实体对象的属性进行校验,并展示了如何在Xaml中结合MaterialDesign风格,以不同的样式显示校验结果。
摘要由CSDN通过智能技术生成

一.说明

本文使用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
最后感谢各位大佬支持关注。
在这里插入图片描述


  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值