一、簡介介紹FluentValidation的文章不少,零度編程的介紹我引用下:FluentValidation 是一個基于 .NET 開發(fā)的驗證框架,開源免費,而且優(yōu)雅,支持鏈式操作,易于理解,功能完善,還是可與 MVC5、WebApi2 和 ASP.NET CORE 深度集成,組件內(nèi)提供十幾種常用驗證器,可擴展性好,支持自定義驗證器,支持本地化多語言。 其實它也可以用于WPF屬性驗證,本文主要也是講解該組件在WPF中的使用,F(xiàn)luentValidation官網(wǎng)是: https:/// 。 二、本文需要實現(xiàn)的功能提供WPF界面輸入驗證,采用MVVM方式,需要以下功能:
先看實現(xiàn)效果圖: 三、調(diào)研中遇到的問題簡單屬性:驗證ViewModel的普通屬性比較簡單,可以參考FluentValidation官網(wǎng):鏈接 ,或者國外holymoo大神的代碼: UserValidator.cs 。 復(fù)雜屬性:我遇到的問題是,怎么驗證ViewModel中對象屬性的子屬性?見第二個功能描述,F(xiàn)luentValidation的官網(wǎng)有Complex Properties的例子,但是我試了沒效果,貼上官方源碼截圖: 最后我Google到這篇文章,根據(jù)該鏈接代碼,ViewModel和子屬性都實現(xiàn)IDataErrorInfo接口,即可實現(xiàn)復(fù)雜屬性驗證,文章中沒有具體實現(xiàn),但靈感是從這來的,就不具體說該鏈接代碼了,有興趣的讀者可以點擊鏈接閱讀,下面說說博主自己的研發(fā)步驟(主要就是貼代碼啦,您可以直接拉到文章末尾,那里賦有源碼下載鏈接)。 四、開發(fā)步驟4.1、創(chuàng)建工程、引入庫創(chuàng)建.Net Core WPF模板解決方案(.Net Framework模板也行):WpfFluentValidation,引入Nuget包FluentValidation(8.5.1)。 4.2、創(chuàng)建測試實體類學(xué)生:Student.cs此類用作ViewModel中的復(fù)雜屬性使用,學(xué)生類包含3個屬性:名字、年齡、郵政編碼。此實體需要繼承IDataErrorInfo接口,這是觸發(fā)FluentValidation驗證的關(guān)鍵接口實現(xiàn)。 using System.ComponentModel; using System.Linq; using WpfFluentValidation.Validators; namespace WpfFluentValidation.Models { /// <summary> /// 學(xué)生實體 /// 繼承BaseClasss,即繼承屬性變化接口INotifyPropertyChanged /// 實現(xiàn)IDataErrorInfo接口,用于FluentValidation驗證,必須實現(xiàn)此接口 /// </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、創(chuàng)建學(xué)生驗證器:StudentValidator.cs驗證屬性的寫法有兩種:
本文使用第二種,見下方學(xué)生驗證器代碼: using FluentValidation; using System.Text.Regulars; using WpfFluentValidation.Models; namespace WpfFluentValidation.Validators { public class StudentValidator : AbstractValidator<Student> { public StudentValidator() { RuleFor(vm => vm.Name) .NotEmpty() .WithMessage("請輸入學(xué)生姓名!") .Length(5, 30) .WithMessage("學(xué)生姓名長度限制在5到30個字符之間!"); RuleFor(vm => vm.Age) .GreaterThanOrEqualTo(0) .WithMessage("學(xué)生年齡為整數(shù)!") .ExclusiveBetween(10, 150) .WithMessage($"請正確輸入學(xué)生年齡(10-150)"); RuleFor(vm => vm.Zip) .NotEmpty() .WithMessage("郵政編碼不能為空!") .Must(BeAValidZip) .WithMessage("郵政編碼由六位數(shù)字組成。"); } private static bool BeAValidZip(string zip) { if (!string.IsNullOrEmpty(zip)) { var regex = new Regex(@"\d{6}"); return regex.IsMatch(zip); } return false; } } } 4.4、 創(chuàng)建ViewModel類:StudentViewModel.csStudentViewModel與Student實體類結(jié)構(gòu)類似,都需要實現(xiàn)IDataErrorInfo接口,該類由一個簡單的string屬性(Title)和一個復(fù)雜的Student對象屬性(CurrentStudent)組成,代碼如下: using System; using System.ComponentModel; using System.Linq; using WpfFluentValidation.Models; using WpfFluentValidation.Validators; namespace WpfFluentValidation.ViewModels { /// <summary> /// 視圖ViewModel /// 繼承BaseClasss,即繼承屬性變化接口INotifyPropertyChanged /// 實現(xiàn)IDataErrorInfo接口,用于FluentValidation驗證,必須實現(xiàn)此接口 /// </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和復(fù)雜屬性CurrentStudent),返回錯誤提示字符串,誒,CurrentStudent的驗證器怎么生效的?有興趣的讀者可以研究FluentValidation庫源碼一探究竟,博主表示研究源碼其樂無窮,一時研究一時爽,一直研究一直爽。 4.5 StudentViewModel的驗證器ViewModelValidator.csViewModel的驗證器,相比Student的驗證器StudentValidator,就簡單的多了,因為只需要編寫驗證一個簡單屬性Title的代碼。而復(fù)雜屬性CurrentStudent的驗證器StudentValidator,將被WPF屬性系統(tǒng)自動調(diào)用,即在StudentViewModel的索引器this[string columnName]和Error屬性中調(diào)用,界面觸發(fā)規(guī)則時自動調(diào)用。 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)、復(fù)雜屬性學(xué)生姓名(CurrentStudent.Name)、學(xué)生年齡( CurrentStudent .Age)、學(xué)生郵政編碼( 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./markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com//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> 五、 介紹完畢碼農(nóng)就是這樣,文章基本靠貼代碼,哈哈。 6、源碼同步本文代碼已同步gitee: https:///lsq6/FluentValidationForWpf github: https://github.com/dotnet9/FluentValidationForWPF CSDN: https://download.csdn.net/download/HenryMoore/11984265 |
|