经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » ASP.net » 查看文章
WPF --- TextBox的输入校验
来源:cnblogs  作者:NiueryDiary  时间:2023/11/17 9:19:03  对本文有异议

引言

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

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

  • ValidationRule
  • IDataErrorInfo

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

ValidationRule

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

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

基本用法

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

  1. public class IntegerValidationRule : ValidationRule
  2. {
  3. public int MaxVal { get; set; }
  4. public int MinVal { get; set; }
  5. public override ValidationResult Validate(object value, CultureInfo cultureInfo)
  6. {
  7. string text = value as string;
  8. if (!int.TryParse(text, out int result))
  9. {
  10. return new ValidationResult(false, "Text cannot be empty.");
  11. }
  12. if (result > MaxVal)
  13. {
  14. return new ValidationResult(false, "Value out of upper limit range.");
  15. }
  16. if (result < MinVal)
  17. {
  18. return new ValidationResult(false, "Value out of lower limit range.");
  19. }
  20. return ValidationResult.ValidResult;
  21. }
  22. }

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

  1. public class TestViewModel : INotifyPropertyChanged
  2. {
  3. private TestViewModel() { }
  4. public static TestViewModel Instance { get; } = new TestViewModel();
  5. public event PropertyChangedEventHandler? PropertyChanged;
  6. protected void OnPropertyChanged(string propertyName)
  7. {
  8. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  9. }
  10. private int testField1;
  11. /// <summary>
  12. /// 测试属性1
  13. /// </summary>
  14. public int TestField1
  15. {
  16. get => testField1;
  17. set
  18. {
  19. testField1 = value;
  20. OnPropertyChanged(nameof(TestField1));
  21. }
  22. }
  23. private int testField2;
  24. /// <summary>
  25. /// 测试属性2
  26. /// </summary>
  27. public int TestField2
  28. {
  29. get => testField2;
  30. set
  31. {
  32. testField2 = value;
  33. OnPropertyChanged(nameof(TestField2));
  34. }
  35. }
  36. }

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

image.png

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

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

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

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

代码如下:

  1. <Window
  2. x:Class="WpfApp4.MainWindow"
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  6. xmlns:local="clr-namespace:WpfApp4"
  7. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. Title="MainWindow"
  9. Width="900"
  10. Height="450"
  11. mc:Ignorable="d">
  12. <Window.Resources>
  13. <ControlTemplate x:Key="ValidationTemplate">
  14. <DockPanel>
  15. <TextBlock
  16. Margin="-10,0,0,0"
  17. VerticalAlignment="Center"
  18. FontSize="22"
  19. Foreground="Red"
  20. Text="!" />
  21. </DockPanel>
  22. </ControlTemplate>
  23. <Style TargetType="TextBox">
  24. <Style.Triggers>
  25. <Trigger Property="Validation.HasError" Value="true">
  26. <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
  27. </Trigger>
  28. </Style.Triggers>
  29. </Style>
  30. </Window.Resources>
  31. <Grid>
  32. <Grid.ColumnDefinitions>
  33. <ColumnDefinition Width="1*" />
  34. <ColumnDefinition Width="1*" />
  35. </Grid.ColumnDefinitions>
  36. <StackPanel Grid.Column="0">
  37. <TextBlock
  38. HorizontalAlignment="Center"
  39. FontSize="18"
  40. FontWeight="Bold"
  41. Text="Validation Demo" />
  42. <TextBox
  43. Name="textBox1"
  44. Height="30"
  45. Margin="10"
  46. FontSize="22"
  47. Validation.ErrorTemplate="{StaticResource ValidationTemplate}">
  48. <TextBox.Text>
  49. <Binding Path="TestField1" UpdateSourceTrigger="PropertyChanged">
  50. <Binding.ValidationRules>
  51. <local:IntegerValidationRule
  52. MaxVal="999"
  53. MinVal="5" />
  54. </Binding.ValidationRules>
  55. </Binding>
  56. </TextBox.Text>
  57. </TextBox>
  58. </StackPanel>
  59. </Grid>
  60. </Window>

最后在窗体后台绑定 ViewModel:

  1. public MainWindow()
  2. {
  3. InitializeComponent();
  4. this.DataContext = TestViewModel.Instance;
  5. }

测试

  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 展示在界面。

  1. <StackPanel Grid.Column="1">
  2. <TextBlock
  3. HorizontalAlignment="Center"
  4. FontSize="18"
  5. FontWeight="Bold"
  6. Text="IDataErrorInfo Demo" />
  7. <TextBox
  8. Name="textBox2"
  9. Margin="10"
  10. VerticalAlignment="Center"
  11. FontSize="22"
  12. Text="{Binding TestField2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
  13. <TextBlock
  14. HorizontalAlignment="Center"
  15. FontSize="18"
  16. FontWeight="Bold"
  17. Foreground="Red"
  18. Text="{Binding Error, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
  19. </StackPanel>

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

  1. public class TestViewModel : INotifyPropertyChanged, IDataErrorInfo
  2. {
  3. //省略上文已有代码..。
  4. private string error;
  5. public string Error
  6. {
  7. get => error;
  8. set
  9. {
  10. error = value; OnPropertyChanged(nameof(Error));
  11. }
  12. }
  13. public string this[string columnName]
  14. {
  15. get
  16. {
  17. switch (columnName)
  18. {
  19. case nameof(TestField2):
  20. return CheckTestFild2();
  21. default:
  22. return null;
  23. }
  24. }
  25. }
  26. public int MaxVal = 999;
  27. public int MinVal = 5;
  28. private string CheckTestFild2()
  29. {
  30. if (TestField2 > MaxVal)
  31. {
  32. Error = "Value out of upper limit range in viewmodel.";
  33. }
  34. else if (TestField2 < MinVal)
  35. {
  36. Error = "Value out of lower limit range in viewmodel.";
  37. }
  38. else
  39. {
  40. Error = string.Empty;
  41. }
  42. return Error;
  43. }
  44. }

测试

  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模式,依旧能够优雅的做数据校验。

原文链接:https://www.cnblogs.com/pandefu/p/17837358.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号