【问题标题】:Allow only numeric entry in WPF Text Box只允许在 WPF 文本框中输入数字
【发布时间】:2010-11-03 09:06:05
【问题描述】:

我想验证用户输入以确保它们是整数。我该怎么做?我想过使用IDataErrorInfo,这似乎是在 WPF 中进行验证的“正确”方式。所以我尝试在我的 ViewModel 中实现它。

但问题是我的文本框绑定到一个整数字段,并且没有任何需要验证int 是否是int。我注意到 WPF 会自动在文本框周围添加一个红色边框以通知用户错误。基础属性不会更改为无效值。但我想将此通知用户。我该怎么做?

【问题讨论】:

标签: c# wpf validation mvvm


【解决方案1】:

您看到的红色边框实际上是一个 ValidationTemplate,您可以扩展它并为用户添加信息。看这个例子:

    <UserControl.Resources>
        <ControlTemplate x:Key="validationTemplate">
            <Grid>
                <Label Foreground="Red" HorizontalAlignment="Right" VerticalAlignment="Center">Please insert a integer</Label>
                <Border BorderThickness="1" BorderBrush="Red">
                    <AdornedElementPlaceholder />
                </Border>
            </Grid>
        </ControlTemplate>
    </UserControl.Resources>

<TextBox Name="tbValue" Validation.ErrorTemplate="{StaticResource validationTemplate}">

【讨论】:

    【解决方案2】:

    另一种方法是简单地不允许非整数值。 以下实现有点糟糕,我想稍后对其进行抽象以使其更具可重用性,但这是我所做的:

    在我看来后面的代码中(我知道如果你是一个铁杆 mvvm 可能会受到伤害;o)) 我定义了以下函数:

      private void NumericOnly(System.Object sender, System.Windows.Input.TextCompositionEventArgs e)
    {
        e.Handled = IsTextNumeric(e.Text);
    
    }
    
    
    private static bool IsTextNumeric(string str)
    {
        System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]");
        return reg.IsMatch(str);
    
    }
    

    在 XAML 视图中,每个只应该接受整数的文本框 是这样定义的:

       <TextBox Padding="2"  TextAlignment="Right" PreviewTextInput="NumericOnly" Text="{Binding xxx.yyyy}" MaxLength="1" />
    

    关键属性是 PreviewTextInput

    【讨论】:

    • 这不会处理空格。我该如何处理?
    • IsTextNumeric 对非数字文本返回 true。更易读的解决方案是将正则表达式更改为 [0-9] 并设置 e.Handled = !IsTextNumeric,因此当文本为数字时,事件会冒泡。或者将方法名称更改为 IsTextNotNumeric :)
    • stackoverflow.com/a/1268648/419348 引入了同样的方法。此外,它还可以防止粘贴错误的数据。
    【解决方案3】:

    我们可以对文本框更改事件进行验证。 以下实现可防止数字和小数点以外的按键输入。

    private void textBoxNumeric_TextChanged(object sender, TextChangedEventArgs e)
    {
            TextBox textBox = sender as TextBox;
            Int32 selectionStart = textBox.SelectionStart;
            Int32 selectionLength = textBox.SelectionLength;
            String newText = String.Empty;
            int count = 0;
            foreach (Char c in textBox.Text.ToCharArray())
            {
                if (Char.IsDigit(c) || Char.IsControl(c) || (c == '.' && count == 0))
                {
                    newText += c;
                    if (c == '.')
                        count += 1;
                }
            }
            textBox.Text = newText;
            textBox.SelectionStart = selectionStart <= textBox.Text.Length ? selectionStart : textBox.Text.Length;    
    }
    

    【讨论】:

      【解决方案4】:

      如果您在 WPF 中工作,最好使用支持所有平台和来自 Presentationcore.dll 的 PreviewTextInput 事件

      示例如下:

      private void TextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
          {
              if ((e.Text) == null || !(e.Text).All(char.IsDigit))
              {
                  e.Handled = true;
              }
          }
      

      【讨论】:

        【解决方案5】:

        这是在 WPF 中使用正则表达式创建数字字段的方法。

        XAML:

        <TextBox PreviewTextInput="NumberValidationTextBox"></TextBox>
        

        后面的代码:

        private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
        {
        Regex regex = new Regex("[^0-9]+");
        e.Handled = regex.IsMatch(e.Text);
        }
        

        【讨论】:

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