のC#WPFアプリケーションでFluentValidation

 

I.はじめに

多くはFluentValidationの記事を紹介し、ゼロプログラミングはで引用を紹介してくれた:WebApi2 FluentValidationは、チェーンオペレーションをサポートし、簡単に、理解して機能を改善するために、.NET開発、オープンソースの自由、そしてエレガントに基づいて検証フレームワークであるかMVC5、とし、 ASP.NET CORE深い統合、アセンブリ内にダースの共通のバリデータを提供し、スケーラビリティ、カスタム検証のためのサポート、多言語ローカライズのサポート。

実際には、それはまた、WPFのプロパティを検証するために使用することができ、この論文はまた、WPFコンポーネントの使用を説明し、FluentValidation公式ウェブサイトは次のとおりです。  https://fluentvalidation.net/  。

第二に、紙は、機能を実装する必要があります

WPFインターフェイスはMVVMの実施形態では、以下の機能を使用して、入力検証を提供します。

  1. シンプルViewModelに定義された属性を確認します。
  2. 複雑なプロパティビューモデルを検証できるようなVMなどのオブジェクトのプロパティのサブプロパティとして、定義された彼の名前、年齢などを確認するために、学生の学生、必要性を属性。
  3. 検証は、単純に2つのスタイルを提供することができます。
  4. いいえ、それは午前3時00の前にあります...

レンダリングの実現を見てください:

のC#WPFアプリケーションでFluentValidation

第三に、研究の問題点

単純属性:比較的簡単です、あなたはFluentValidation公式サイトを参照することができViewModelに共通の属性を確認します。リンク  、または外国holymooコードの神:  UserValidator.cs  。

複合属性:私の問題は、オブジェクトのプロパティで、サブのViewModelプロパティを確認する方法ですか?、第二の機能説明を参照してくださいFluentValidationの公式サイト複雑なプロパティの例が、私は公式のソーススクリーンショット接辞、効果を試していません。

のC#WPFアプリケーションでFluentValidation

最后我Google到这篇文章,根据该链接代码,ViewModel和子属性都实现IDataErrorInfo接口,即可实现复杂属性验证,文章中没有具体实现,但灵感是从这来的,就不具体说该链接代码了,有兴趣可以点击链接阅读,下面贴上代码。

四、开发步骤

4.1、创建工程、引入库

创建.Net Core WPF模板解决方案(.Net Framework模板也行):WpfFluentValidation,引入Nuget包FluentValidation(8.5.1)。

4.2、创建测试实体类学生:Student.cs

此类用作ViewModel中的复杂属性使用,学生类包含3个属性:名字、年龄、邮政编码。此实体需要继承IDataErrorInfo接口,触发FluentValidation必须的。

using System.ComponentModel;
using System.Linq;
using WpfFluentValidation.Validators;

namespace WpfFluentValidation.Models
{
    /// <summary>
    /// 学生实体
    /// 继承BaseClasss,即继承属性变化接口INotifyPropertyChanged
    /// 实现IDataErrorInfo接口,用于FluentValidation验证,必须实现此接口
    /// </summary>
    public class Student : BaseClass, IDataErrorInfo
    {
        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                if (value != name)
                {
                    name = value;
                    OnPropertyChanged(nameof(Name));
                }
            }
        }
        private int age;
        public int Age
        {
            get { return age; }
            set
            {
                if (value != age)
                {
                    age = value;
                    OnPropertyChanged(nameof(Age));
                }
            }
        }
        private string zip;
        public string Zip
        {
            get { return zip; }
            set
            {
                if (value != zip)
                {
                    zip = value;
                    OnPropertyChanged(nameof(Zip));
                }
            }
        }

        public string Error { get; set; }

        public string this[string columnName]
        {
            get
            {
                if (validator == null)
                {
                    validator = new StudentValidator();
                }
                var firstOrDefault = validator.Validate(this)
                    .Errors.FirstOrDefault(lol => lol.PropertyName == columnName);
                return firstOrDefault?.ErrorMessage;
            }
        }

        private StudentValidator validator { get; set; }
    }
}

4.3、创建学生验证器:StudentValidator.cs

验证属性的写法有两种:

  1. 可以在实体属性上方添加特性(本文不作特别说明,百度文章介绍很多);
  2. 通过代码的形式添加,如下方,创建一个验证器类,继承自AbstractValidator,在此验证器构造函数中写规则验证属性,方便管理。

本文使用第二种,见下方学生验证器代码:

using FluentValidation;
using System.Text.RegularExpressions;
using WpfFluentValidation.Models;

namespace WpfFluentValidation.Validators
{
    public class StudentValidator : AbstractValidator<Student>
    {
        public StudentValidator()
        {
            RuleFor(vm => vm.Name)
                    .NotEmpty()
                    .WithMessage("请输入学生姓名!")
                .Length(5, 30)
                .WithMessage("学生姓名长度限制在5到30个字符之间!");

            RuleFor(vm => vm.Age)
                .GreaterThanOrEqualTo(0)
                .WithMessage("学生年龄为整数!")
                .ExclusiveBetween(10, 150)
                .WithMessage($"请正确输入学生年龄(10-150)");

            RuleFor(vm => vm.Zip)
                .NotEmpty()
                .WithMessage("邮政编码不能为空!")
                .Must(BeAValidZip)
                .WithMessage("邮政编码由六位数字组成。");
        }

        private static bool BeAValidZip(string zip)
        {
            if (!string.IsNullOrEmpty(zip))
            {
                var regex = new Regex(@"\d{6}");
                return regex.IsMatch(zip);
            }
            return false;
        }
    }
}

4.4、 创建ViewModel类:StudentViewModel.cs

StudentViewModel与Student实体类结构类似,都需要实现IDataErrorInfo接口,该类由一个简单的string属性(Title)和一个复杂的Student对象属性(CurrentStudent)组成,代码如下:

using System;
using System.ComponentModel;
using System.Linq;
using WpfFluentValidation.Models;
using WpfFluentValidation.Validators;

namespace WpfFluentValidation.ViewModels
{
    /// <summary>
    /// 视图ViewModel
    /// 继承BaseClasss,即继承属性变化接口INotifyPropertyChanged
    /// 实现IDataErrorInfo接口,用于FluentValidation验证,必须实现此接口
    /// </summary>
    public class StudentViewModel : BaseClass, IDataErrorInfo
    {
        private string title;
        public string Title
        {
            get { return title; }
            set
            {
                if (value != title)
                {
                    title = value;
                    OnPropertyChanged(nameof(Title));
                }
            }
        }

        private Student currentStudent;
        public Student CurrentStudent
        {
            get { return currentStudent; }
            set
            {
                if (value != currentStudent)
                {
                    currentStudent = value;
                    OnPropertyChanged(nameof(CurrentStudent));
                }
            }
        }

        public StudentViewModel()
        {
            CurrentStudent = new Student()
            {
                Name = "李刚的儿",
                Age = 23
            };
        }


        public string this[string columnName]
        {
            get
            {
                if (validator == null)
                {
                    validator = new ViewModelValidator();
                }
                var firstOrDefault = validator.Validate(this)
                    .Errors.FirstOrDefault(lol => lol.PropertyName == columnName);
                return firstOrDefault?.ErrorMessage;
            }
        }
        public string Error
        {
            get
            {
                var results = validator.Validate(this);
                if (results != null && results.Errors.Any())
                {
                    var errors = string.Join(Environment.NewLine, results.Errors.Select(x => x.ErrorMessage).ToArray());
                    return errors;
                }

                return string.Empty;
            }
        }

        private ViewModelValidator validator;
    }
}

仔细看上方代码,对比Student.cs,重写自IDataErrorInfo的Error属性定义有所不同。Student.cs对Error基本未做修改,而StudentViewModel.cs有变化,get器中验证属性(简单属性Title和复杂属性CurrentStudent),返回错误提示字符串,诶,CurrentStudent的验证器怎么生效的?有兴趣的大佬可以研究FluentValidation库源码一探究竟,我没有深究。

4.5 StudentViewModel的验证器ViewModelValidator.cs

ViewModel的验证器,相比Student的验证器StudentValidator,就简单的多了,因为只需要编写验证一个简单属性Title的代码。而复杂属性CurrentStudent的验证器StudentValidator,将被WPF属性系统自动调用,即在StudentViewModel的索引器this[string columnName]和Error属性中调用,界面触发规则时自动调用,具体是什么机制我没有仔细研究,有兴趣的大佬可以研究源码。

using FluentValidation;
using WpfFluentValidation.ViewModels;

namespace WpfFluentValidation.Validators
{
    public class ViewModelValidator:AbstractValidator<StudentViewModel>
    {
        public ViewModelValidator()
        {
            RuleFor(vm => vm.Title)
                .NotEmpty()
                .WithMessage("标题长度不能为空!")
                .Length(5, 30)
                .WithMessage("标题长度限制在5到30个字符之间!");
        }
    }
}

4.6 辅助类BaseClass.cs

简单封装INotifyPropertyChanged接口

using System.ComponentModel;

namespace WpfFluentValidation
{
    public class BaseClass : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

4.7 、视图StudentView.xaml

用户直接接触的视图文件来了,比较简单,提供简单属性标题(Title)、复杂属性学生姓名(CurrentStudent.Name)、学生年龄( CurrentStudent .Age)、学生邮政编码( CurrentStudent .Zip)验证,xaml代码如下:

<UserControl x:Class="WpfFluentValidation.Views.StudentView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfFluentValidation.Views"
             xmlns:vm="clr-namespace:WpfFluentValidation.ViewModels"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <UserControl.DataContext>
        <vm:StudentViewModel/>
    </UserControl.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <GroupBox Header="ViewModel直接属性验证">
            <StackPanel Orientation="Horizontal">
                <Label Content="标题:"/>
                <TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
                         Style="{StaticResource ErrorStyle1}"/>
            </StackPanel>
        </GroupBox>
        <GroupBox Header="ViewModel对象属性CurrentStudent的属性验证" Grid.Row="1">
            <StackPanel>
                <StackPanel Orientation="Horizontal">
                    <Label Content="姓名:"/>
                    <TextBox Text="{Binding CurrentStudent.Name, UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
                         Style="{StaticResource ErrorStyle2}"/>
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <Label Content="年龄:"/>
                    <TextBox Text="{Binding CurrentStudent.Age, UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
                         Style="{StaticResource ErrorStyle2}"/>
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <Label Content="邮编:" />
                    <TextBox Text="{Binding CurrentStudent.Zip, UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
                         Style="{StaticResource ErrorStyle2}"/>
                </StackPanel>
            </StackPanel>
        </GroupBox>
    </Grid>
</UserControl>

4.8 、错误提示样式

本文提供了两种样式,具体效果见前面的截图,代码如下:

<Application x:Class="WpfFluentValidation.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfFluentValidation"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Style TargetType="StackPanel">
            <Setter Property="Margin" Value="0 5"/>
        </Style>
        <!--第一种错误样式,红色边框-->
        <Style TargetType="{x:Type TextBox}" x:Key="ErrorStyle1">
            <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>

        <!--第二种错误样式,右键文字提示-->
        <Style TargetType="{x:Type TextBox}" x:Key="ErrorStyle2">
            <Setter Property="Width" Value="200"/>
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <StackPanel Orientation="Horizontal">
                            <AdornedElementPlaceholder x:Name="textBox"/>
                            <TextBlock Margin="10" Text="{Binding [0].ErrorContent}" Foreground="Red"/>
                        </StackPanel>
                    </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>
    </Application.Resources>
</Application>

五、 介绍完毕

码农就是这样,文章基本贴代码,哈哈。

6、源码同步

この記事のコード同期gitee:  https://gitee.com/lsq6/FluentValidationForWpf

githubの:  https://github.com/dotnet9/FluentValidationForWPF

CSDN:  https://download.csdn.net/download/HenryMoore/11984265

免責事項:ブログブロガーDotnet9元の記事についてこの記事で、「オオカミの最後に砂漠」、CC 4.0 BY-SAの著作権契約書に従って、再現し、元のソースのリンクと、この文を添付してください。

オリジナルリンクします。https://dotnet9.com/ P = 853?

おすすめ

転載: www.cnblogs.com/lsq6/p/fluentvalidation-csharp-wpf.html