2010-11-03 128 views
12

我想验证用户输入以确保它们是整数。我该怎么做?我想到了使用IDataErrorInfo这似乎是在WPF中进行验证的“正确”方法。所以我尝试在ViewModel中实现它。只允许在WPF文本框中输入数字

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

回答

11

您看到的红色边框实际上是一个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}"> 
14

另一种方法是不允许非整数值。 下面的实现有点烂,我想稍后将其抽象出来,以便它可以重复使用,但这里是我所做的:

在我的视图后面的代码中(我知道这个是,如果你是一个铁杆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

+2

这不会处理空白。我如何处理DEM? – 2012-01-20 10:13:01

+0

稍后修剪它们? – 2012-03-09 16:19:50

+1

对于非数字文本,IsTextNumeric返回true。更可读的解决方案是将正则表达式更改为[0-9]并设置e.Handled =!IsTextNumeric,以便在文本为数字时冒出事件。这或更改方法名称IsTextNotNumeric :) – 2012-04-22 22:35:11

8

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

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;  
} 
+0

非常有帮助...... – 2015-09-10 08:30:46

+0

真的很有帮助。 – 2016-02-23 04:12:11

相关问题