首页 > 其他分享 >WPF --- TextBox的输入校验

WPF --- TextBox的输入校验

时间:2023-11-16 21:57:18浏览次数:25  
标签:ValidationRule string int 校验 --- WPF out public TextBox

引言

在WPF应用程序开发中,数据校验是确保用户输入数据的正确性和完整性的重要一环。

之前在做一些参数配置功能时,最是头疼各种参数校验,查阅一些资料后,我总结了数据校验方式有两种:

  • ValidationRule
  • IDataErrorInfo

接下来分别介绍这两种校验方式。

ValidationRule

ValidationRule 是一个抽象类,提供了抽象方法 Validate(), 它是WPF中用于数据验证的一种机制,它可以在用户输入数据之前或之后执行自定义的验证逻辑。可以轻松地实现对数据的格式、范围、逻辑等方面的验证,并在验证失败时提供相应的反馈信息。

ValidationRule主要作用域在前端页面上

基本用法

首先创建一个 ValidationRule,我这里设定了两个属性 MaxValMinVal,然后在 Validate() 方法中判断空、判断大于上限或小于下限,然后在符合条件是,返回 ValidationResult,并给出错误提示:

public class IntegerValidationRule : ValidationRule
{
    public int MaxVal { get; set; }
    public int MinVal { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        string text = value as string;

        if (!int.TryParse(text, out int result))
        {
            return new ValidationResult(false, "Text cannot be empty.");
        }

        if (result > MaxVal)
        {
            return new ValidationResult(false, "Value out of upper limit range.");
        }

        if (result < MinVal)
        {
            return new ValidationResult(false, "Value out of lower limit range.");
        }

        return ValidationResult.ValidResult;
    }
}

接下来创建有个测试使用的 ViewModel:

public class TestViewModel : INotifyPropertyChanged
{
    private TestViewModel() { }

    public static TestViewModel Instance { get; } = new TestViewModel();

    public event PropertyChangedEventHandler? PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private int testField1;
    /// <summary>
    /// 测试属性1
    /// </summary>
    public int TestField1
    {
        get => testField1;
        set
        {
            testField1 = value;
            OnPropertyChanged(nameof(TestField1));
        }
    }

    private int testField2;
    /// <summary>
    /// 测试属性2
    /// </summary>
    public int TestField2
    {
        get => testField2;
        set
        {
            testField2 = value;
            OnPropertyChanged(nameof(TestField2));
        }
    }
}


在测试之前,我们可以先看一下 Binding 的方法列表:

image.png

可以看到 ValidationRulesBinding 下的集合,这意味着 ValidationRule 是在 Binding 下使用且可以执行多个校验规则。校验时按照顺序依次校验。

接下来我们创建一个WPF应用程序,在界面添加 TextBox,命名为”textbox1“,将文本绑定在 TestViewModelTestField1

且为Validation.ErrorTemplate 绑定一个模板,这里绑定了一个红色的感叹号。

然后为 TextBox 设置触发器,当 Validation.HasErrortrue时,将 ToolTip 绑定校验失败的错误提示。

代码如下:

<Window
    x:Class="WpfApp4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:WpfApp4"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="MainWindow"
    Width="900"
    Height="450"
    mc:Ignorable="d">
    <Window.Resources>
        <ControlTemplate x:Key="ValidationTemplate">
            <DockPanel>
                <TextBlock
                    Margin="-10,0,0,0"
                    VerticalAlignment="Center"
                    FontSize="22"
                    Foreground="Red"
                    Text="!" />

            </DockPanel>
        </ControlTemplate>

        <Style TargetType="TextBox">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="1*" />
        </Grid.ColumnDefinitions>
        <StackPanel Grid.Column="0">
            <TextBlock
                HorizontalAlignment="Center"
                FontSize="18"
                FontWeight="Bold"
                Text="Validation Demo" />
            <TextBox
                Name="textBox1"
                Height="30"
                Margin="10"
                FontSize="22"
                Validation.ErrorTemplate="{StaticResource ValidationTemplate}">
                <TextBox.Text>
                    <Binding Path="TestField1" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <local:IntegerValidationRule
                                MaxVal="999"
                                MinVal="5" />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>

        </StackPanel>
    </Grid>
</Window>

最后在窗体后台绑定 ViewModel:

public MainWindow()
{
    InitializeComponent();
    this.DataContext =  TestViewModel.Instance;
}

测试

  1. 为空时,出现红色叹号,ToolTip 提示 "Text cannot be empty."
    image.png

  2. 小于下限时,出现红色叹号,ToolTip 提示 "Value out of lower limit range."
    image.png

  3. 大于上限时,出现红色叹号,ToolTip 提示 "Value out of upper limit range."
    image.png

IDataErrorInfo

IDataErrorInfo 是一个接口,Viewmodel 实现接口用于在后台,提供数据验证和错误信息。

IDataErrorInfo 主要作用域为后台 ViewModel
该接口包含两个成员:Errorthis[string columnName]。这两个成员允许你在数据绑定时提供验证错误信息。

基本用法

接下来,在程序里添加 TextBox,命名为”textbox2“,并添加一个 TextBlock 绑定 Error 展示在界面。

<StackPanel Grid.Column="1">
    <TextBlock
        HorizontalAlignment="Center"
        FontSize="18"
        FontWeight="Bold"
        Text="IDataErrorInfo Demo" />
    <TextBox
        Name="textBox2"
        Margin="10"
        VerticalAlignment="Center"
        FontSize="22"
        Text="{Binding TestField2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
     <TextBlock
         HorizontalAlignment="Center"
         FontSize="18"
         FontWeight="Bold"
         Foreground="Red"
         Text="{Binding Error, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>

后台 TestViweModel 实现 IDataErrorInfo,依旧是判断上限值和下限值,此处不判断空,是因为后台 TestField2 类型是Int,为空时不会赋值,代码如下:

public class TestViewModel : INotifyPropertyChanged, IDataErrorInfo
{
    //省略上文已有代码..。
    
    private string error;
    public string Error
    {
        get => error;
        set
        {
            error = value; OnPropertyChanged(nameof(Error));
        }
    }
    public string this[string columnName]
    {
        get
        {
            switch (columnName)
            {
                case nameof(TestField2):
                    return CheckTestFild2();
                default:
                    return null;
            }
        }
    }

    public int MaxVal = 999;
    public int MinVal = 5;

    private string CheckTestFild2()
    {
        if (TestField2 > MaxVal)
        {
            Error = "Value out of upper limit range in viewmodel.";
        }
        else if (TestField2 < MinVal)
        {
            Error = "Value out of lower limit range  in viewmodel.";
        }
        else
        {
            Error = string.Empty;
        }
        
        return Error;
    }
}

测试

  1. 小于下限时,出现红色文字提示,ToolTip 提示 "Value out of lower limit range in viewmodel."
    image.png

  2. 大于上限时,出现红色文字提示,ToolTip 提示 "Value out of upper limit range in viewmodel."
    image.png

小结

以上两种数据校验(IDataErrorInfoValidationRule)的方式,均可以实现自定义数据校验,例如对数据的格式、范围、逻辑等方面的验证,并在验证失败时提供相应的反馈信息。

ValidationRule适用于在界面做数据校验,且可以定义多个校验规则。

ValidationRule适用于在ViewModel做数据校验,可以做一些无法在前端页面做的事情,比如出现异常值是还原为默认值。

所以两者既可以单独使用,也可以组合使用,即使使用MVVM模式,依旧能够优雅的做数据校验。

标签:ValidationRule,string,int,校验,---,WPF,out,public,TextBox
From: https://www.cnblogs.com/pandefu/p/17837358.html

相关文章

  • 无涯教程-Dart - Optional Parameters with Default Values函数
    默认情况下,还可以为函数参数分配值,但是,此类参数也可以是显式传递的值。语法function_name(param1,{param2=default_value}){//......}示例voidmain(){test_param(123);}voidtest_param(n1,{s1:12}){print(n1);print(s1);}它应该返回......
  • esp32笔记[10]-rust驱动ssd1306显示屏
    摘要使用rust(no-std)环境和esp-hal库实现SSD1306显示屏(128x64)显示bmp图片.平台信息esp32(模组:ESP32-WROOM-32D)(xtensalx6)(xtensa-esp32-none-elf)rust超链接esp32笔记[7]-使用rust+zig开发入门原理简介rust的include_bytes!宏Rust的include_bytes!宏可以用......
  • openGauss学习笔记-125 openGauss 数据库管理-设置账本数据库-校验账本数据一致性
    openGauss学习笔记-125openGauss数据库管理-设置账本数据库-校验账本数据一致性125.1前提条件数据库正常运行,并且对防篡改数据库执行了一系列增、删、改等操作,保证在查询时段内有账本操作记录结果产生。125.2背景信息账本数据库校验功能目前提供两种校验接口,分别为:ledger......
  • matlab实现频谱感知-认知无线电
    1、前言\(\quad\)频谱感知的方法有很多,比如匹配滤波探测,能量检测,静态循环特征探测等方法,然后最近因为在用硬件做能量检测,所以本文主要是说了如何用matlab实现能量检测,它的大概流程就是:信号采样->模平方->累加->判决,其他的方法不再了解。2、一些前置知识:恒虚警率阈值......
  • JavaWeb--响应字符&字节数据
    Response响应字符数据 //text/html解码html,charset解码汉字response.setContentType("text/html;charset=utf-8");//1、获取字符输入流PrintWriterwriter=response.getWriter();writer.write("你好");writer.write("<h1>124</h1>");响应字节数据添加一个i......
  • 【漏洞复现】JumpServer伪随机密码重置漏洞[CVE-2023-42820]
    Jumperver是飞致云公司(https://www.jumpserver.org)旗下开源的堡垒机,是国内最受欢迎的开源堡垒机之一。小编也经常使用,也介绍给一些运维的客户使用,简直是运维神器。2023年9月爆出CVE-2023-42820造成任意用户密码重置漏洞。大概就是Jumpserver的一个第三方库django-simp......
  • 学期2023-2024-1 20231401 《计算机基础与程序设计》第八周学习总结
    学期2023-2024-120231401《计算机基础与程序设计》第八周学习总结作业信息这个作业属于哪个课程2023-2024-1-计算机基础与程序设计这个作业要求在哪里2023-2024-1计算机基础与程序设计第八周作业这个作业的目标《计算机科学概论》第9章《C语言程序设计》第7章并......
  • 无涯教程-Dart - Optional named parameter函数
    与位置参数不同,必须在传递值时指定参数名称,花括号{}可用于指定可选的命名参数。语法 - 声明函数voidfunction_name(a,{optional_param1,optional_param2}){}语法 - 调用函数function_name(optional_param:value,…);示例voidmain(){test_param(123);......
  • BLOG-2
    一.前言菜单四菜单四是在菜单三的基础上迭代的,难度较大,因为要求有很多,这次大作业只要这一道题,但是也是要花费很长时间的一些知识点:类和对象:在代码中定义了几个类,如MenuItem(菜单项)、OrderItem(订单项)、TableOrder(桌子订单)和Table(桌子),它们用于组织和存储相关的数据和行为。......
  • HTTP 响应字段 Transfer-Encoding 的作用介绍
    Transfer-Encoding字段是HTTP响应头部的一部分,用于指示在传输响应正文(responsebody)时所使用的传输编码方式。在HTTP通信中,响应正文可以以多种不同的编码方式传输,其中一种方式是chunked传输编码。本文将详细介绍Transfer-Encoding字段的含义和chunked传输编码,以及提供示例来解释这......