《Dotnet9》系列-FluentValidation在C# WPF中的應用

来源:https://www.cnblogs.com/Dotnet9-com/archive/2019/12/17/12052218.html
-Advertisement-
Play Games

時間如流水,只能流去不流回! 點贊再看,養成習慣,這是您給我創作的動力! 本文 Dotnet9 https://dotnet9.com 已收錄,站長樂於分享dotnet相關技術,比如Winform、WPF、ASP.NET Core等,亦有C++桌面相關的Qt Quick和Qt Widgets等,只分 ...


時間如流水,只能流去不流回!

點贊再看,養成習慣,這是您給我創作的動力!

本文 Dotnet9 https://dotnet9.com 已收錄,站長樂於分享dotnet相關技術,比如Winform、WPF、ASP.NET Core等,亦有C++桌面相關的Qt Quick和Qt Widgets等,只分享自己熟悉的、自己會的。

一、簡介

介紹FluentValidation的文章不少,零度編程的介紹我引用下:FluentValidation 是一個基於 .NET 開發的驗證框架,開源免費,而且優雅,支持鏈式操作,易於理解,功能完善,還是可與 MVC5、WebApi2 和 ASP.NET CORE 深度集成,組件內提供十幾種常用驗證器,可擴展性好,支持自定義驗證器,支持本地化多語言。

其實它也可以用於WPF屬性驗證,本文主要也是講解該組件在WPF中的使用,FluentValidation官網是: https://fluentvalidation.net/ 。

二、本文需要實現的功能

提供WPF界面輸入驗證,採用MVVM方式,需要以下功能:

  1. 能驗證ViewModel中定義的簡單屬性;
  2. 能驗證ViewModel中定義的複雜屬性,比如對象屬性的子屬性,如VM有個學生屬性Student,需要驗證他的姓名、年齡等;
  3. 能簡單提供兩種驗證樣式;
  4. 沒有了,就是前面3點…

先看實現效果圖:

《Dotnet9》系列-FluentValidation在C# WPF中的應用

三、調研中遇到的問題

簡單屬性:驗證ViewModel的普通屬性比較簡單,可以參考FluentValidation官網:鏈接 ,或者國外holymoo大神的代碼: UserValidator.cs 。

複雜屬性:我遇到的問題是,怎麼驗證ViewModel中對象屬性的子屬性?見第二個功能描述,FluentValidation的官網有Complex Properties的例子,但是我試了沒效果,貼上官方源碼截圖:

《Dotnet9》系列-FluentValidation在C# WPF中的應用

最後我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


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 對於RuntimeException 做java開發的朋友想必不會陌生,可以用於事物的回滾操作。異常類型也有很多種,寫這篇文章主要是為了總結自己開發中遇到的一些異常類型 以便幫助大家遇到相應的報錯找不出原因,不廢話直接入正題: 1.java.lang.NullPointerException 空指針 ...
  • 很多人都知道,阿裡巴巴在2017發佈了《阿裡巴巴Java開發手冊》,前後推出了很多個版本,併在後續推出了與之配套的IDEA插件和書籍。 相信很多Java開發都或多或少看過這份手冊,這份手冊有7個章節,覆蓋了編程規約、異常日誌、單元測試、安全規約、MySQL資料庫、工程結構以及設計規約等方面。 這份規 ...
  • 有參裝飾器 1,將@ 與函數分開@ timmerout(flag) 返回了timmer 2,將@timmer結合 PS:遇到問題沒人解答?需要Python學習資料?可以加點擊下方鏈接自行獲取 note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee3 ...
  • 時間如流水,只能流去不流回! 點贊再看,養成習慣,這是您給我創作的動力! 本文 Dotnet9 https://dotnet9.com 已收錄,站長樂於分享dotnet相關技術,比如Winform、WPF、ASP.NET Core等,亦有C++桌面相關的Qt Quick和Qt Widgets等,只分 ...
  • 時間如流水,只能流去不流回! 點贊再看,養成習慣,這是您給我創作的動力! 本文 Dotnet9 https://dotnet9.com 已收錄,站長樂於分享dotnet相關技術,比如Winform、WPF、ASP.NET Core等,亦有C++桌面相關的Qt Quick和Qt Widgets等,只分 ...
  • 時間如流水,只能流去不流回! 點贊再看,養成習慣,這是您給我創作的動力! 本文 Dotnet9 https://dotnet9.com 已收錄,站長樂於分享dotnet相關技術,比如Winform、WPF、ASP.NET Core等,亦有C++桌面相關的Qt Quick和Qt Widgets等,只分 ...
  • 時間如流水,只能流去不流回! 點贊再看,養成習慣,這是您給我創作的動力! 本文 Dotnet9 https://dotnet9.com 已收錄,站長樂於分享dotnet相關技術,比如Winform、WPF、ASP.NET Core等,亦有C++桌面相關的Qt Quick和Qt Widgets等,只分 ...
  • 時間如流水,只能流去不流回! 點贊再看,養成習慣,這是您給我創作的動力! 本文 Dotnet9 https://dotnet9.com 已收錄,站長樂於分享dotnet相關技術,比如Winform、WPF、ASP.NET Core等,亦有C++桌面相關的Qt Quick和Qt Widgets等,只分 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...