2010-11-03 81 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

相關問題