時間如流水,只能流去不流回!git
點贊再看,養成習慣,這是您給我創做的動力!github
本文 Dotnet9 https://dotnet9.com 已收錄,站長樂於分享dotnet相關技術,好比Winform、WPF、ASP.NET Core等,亦有C++桌面相關的Qt Quick和Qt Widgets等,只分享本身熟悉的、本身會的。express
介紹FluentValidation的文章很多,零度編程的介紹我引用下:FluentValidation 是一個基於 .NET 開發的驗證框架,開源免費,並且優雅,支持鏈式操做,易於理解,功能完善,仍是可與 MVC五、WebApi2 和 ASP.NET CORE 深度集成,組件內提供十幾種經常使用驗證器,可擴展性好,支持自定義驗證器,支持本地化多語言。編程
其實它也能夠用於WPF屬性驗證,本文主要也是講解該組件在WPF中的使用,FluentValidation官網是: https://fluentvalidation.net/ 。xcode
提供WPF界面輸入驗證,採用MVVM方式,須要如下功能:框架
先看實現效果圖:wordpress
簡單屬性:驗證ViewModel的普通屬性比較簡單,能夠參考FluentValidation官網:連接 ,或者國外holymoo大神的代碼: UserValidator.cs 。函數
複雜屬性:我遇到的問題是,怎麼驗證ViewModel中對象屬性的子屬性?見第二個功能描述,FluentValidation的官網有Complex Properties的例子,可是我試了沒效果,貼上官方源碼截圖:post
最後我Google到這篇文章,根據該連接代碼,ViewModel和子屬性都實現IDataErrorInfo接口,便可實現複雜屬性驗證,文章中沒有具體實現,但靈感是從這來的,就不具體說該連接代碼了,有興趣的讀者能夠點擊連接閱讀,下面說說博主本身的研發步驟(主要就是貼代碼啦,您能夠直接拉到文章末尾,那裏賦有源碼下載連接)。測試
建立.Net Core WPF模板解決方案(.Net Framework模板也行):WpfFluentValidation,引入Nuget包FluentValidation(8.5.1)。
此類用做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; } } }
驗證屬性的寫法有兩種:
本文使用第二種,見下方學生驗證器代碼:
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; } } }
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庫源碼一探究竟,博主表示研究源碼其樂無窮,一時研究一時爽,一直研究一直爽。
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個字符之間!"); } } }
簡單封裝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)); } } } }
用戶直接接觸的視圖文件來了,比較簡單,提供簡單屬性標題(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>
本文提供了兩種樣式,具體效果見前面的截圖,代碼以下:
<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>
碼農就是這樣,文章基本靠貼代碼,哈哈。
本文代碼已同步gitee: https://gitee.com/lsq6/FluentValidationForWpf
github: https://github.com/dotnet9/FluentValidationForWPF
CSDN: https://download.csdn.net/download/HenryMoore/11984265