【问题标题】:WPF Textfield ValidationWPF 文本字段验证
【发布时间】:2016-07-30 11:25:21
【问题描述】:

我在 WPF 中有一个文本字段,我想验证用户输入,我发现很多示例可以完成我想要的部分,但没有一个可以全部完成。

它必须只允许数字(0-9) 只有一位小数 不允许多个 '.'大多数解决方案似乎都允许, 最小输入数必须是 最大 999.9

目前我发现的最佳解决方案是使用正则表达式

new Regex(@"[^0-9.]+") 

但这显然不限制小数位数或小数点数。也没有最小值或最大值

只能指出我正确的方向吗?

谢谢

【问题讨论】:

    标签: wpf validation textfield


    【解决方案1】:

    更简洁的解决方案可能是将文本框绑定到 double(或 decimal)值,这将为您提供自动数字和小数点规则,并添加一个 [Range] 属性的最小值和最大值:

    [Range(0, 999.9), "Error message"]
    public double myValue { get; set; }
    

    或者,如果您想真正防止输入无效输入,请为文本框实现OnKeyDown 事件处理程序并尝试将输入转换为数字。如果失败拒绝输入,或者如果成功但数字超出您的范围,则拒绝输入。这不是一个理想的解决方案。

    【讨论】:

      【解决方案2】:

      我通常使用这种方法,因为它简单且灵活。只是正则表达式和普通条件逻辑的一个不起眼的混合物。同样的模式可以应用于几乎任何形式的文本输入验证。

      视图模型

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      using System.ComponentModel;
      using System.Text.RegularExpressions;
      
      namespace WpfApplication7
      {
          public class ViewModel : INotifyPropertyChanged
          {
              Regex _inputRegex;
              public ViewModel()
              {
                  _inputRegex = new Regex(@"^([0-9])+(([.])?([0-9])+)?$");
              }
              private string _input = "0";
              public string Input
              {
                  get
                  {
                      return _input;
                  }
                  set
                  {
                     _input = value;
                     RaisePropertyChanged("Input");
                     RaisePropertyChanged("InputValid");
                  }
              }
              public bool InputValid {
                  get
                  {
                      if(_inputRegex.IsMatch(_input))
                      {
                          //If regex pattern is satisfied, this value is safe
                          double value = Convert.ToDouble(_input);
      
                          //so just apply conditional logic here
                          return value >= 0 && value <= 999.9;
                      }
                      else
                      {
                          return false;
                      }
                  }        
              }
              public event PropertyChangedEventHandler PropertyChanged;
              public void RaisePropertyChanged(string property)
              {
                  PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
              }
          }
      }
      

      观点

      <Window x:Class="WpfApplication7.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
              xmlns:local="clr-namespace:WpfApplication7"
              mc:Ignorable="d"
              Title="MainWindow" Height="350" Width="525">
          <Window.DataContext>
              <local:ViewModel />
          </Window.DataContext>
          <Window.Resources>
              <Style TargetType="FrameworkElement" >
                  <Setter Property="HorizontalAlignment" Value="Center" />
                  <Setter Property="VerticalAlignment" Value="Center" />
              </Style>
              <Style TargetType="TextBox">
                  <Setter Property="Width" Value="100" />
                  <Setter Property="Height" Value="24" />
                  <Setter Property="VerticalContentAlignment" Value="Center" />
                  <Setter Property="Margin" Value="10" />
              </Style>
              <Style  TargetType="TextBlock" x:Key="default_textblock">
                  <Setter Property="Height" Value="18" />
                  <Setter Property="Margin" Value="10" />
              </Style>
              <Style TargetType="TextBlock" x:Key="error_textblock" BasedOn="{StaticResource default_textblock}">
                  <Setter Property="Foreground" Value="Red" />
              </Style>
          </Window.Resources>
          <Grid>
              <Grid.RowDefinitions>
                  <RowDefinition Height="60" />
                  <RowDefinition Height="60" />
              </Grid.RowDefinitions>
              <StackPanel Orientation="Horizontal" Grid.Row="0">
                  <TextBlock Text="Enter input: " Style="{StaticResource default_textblock}" />
                  <TextBox Text="{Binding Input, UpdateSourceTrigger=PropertyChanged}" />
              </StackPanel>
              <TextBlock Grid.Row="1" Text="Input not valid. Please enter a number between 0 and 999.9" >
                  <TextBlock.Style>
                      <Style TargetType="TextBlock" BasedOn="{StaticResource error_textblock}">
                          <Setter Property="Visibility" Value="Hidden" />
                          <Style.Triggers>
                              <DataTrigger Binding="{Binding InputValid}" Value="False">
                                  <Setter Property="Visibility" Value="Visible" />
                              </DataTrigger>
                          </Style.Triggers>
                      </Style>
                  </TextBlock.Style>
              </TextBlock>
          </Grid>
      </Window>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-01
        • 2013-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多