我有一個wpf文本框,我想檢查用戶輸入它是否只使用0 1 2 3 4 5 6 7 8 9。小數點的[小數點]字符。我用這個文本框轉換爲十進制後驗證用戶輸入的十進制數
我使用的後續文章爲起點 Regex MatchPreview Text Input exampleregex-to-allow-one-decimal-number-or-a-range-of-decimal-number
這是我的XAML
<TextBox Grid.Column="1" Height="28" HorizontalAlignment="Left" Margin="10,10,0,0" Name="tbTaxFreeLimit" Width="90" VerticalAlignment="Top"
AcceptsTab="True"
PreviewTextInput="tbDecimalCheck_PreviewTextInput"
/>
和C#
private void tbDecimalCheck_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
// Test for decimal
if (IsNumeric(e.Text)==false)
e.Handled = true;
}
private bool IsNumeric(string s)
{
Regex r = new Regex(@"^[0-9]");
return r.IsMatch(s);
}
這個例子工作正常0 1 2 3 4 5 6 7 8 9但我不能輸入十進制po int。
如果我改變了對下面的代碼在它下面有沒有
Regex r = new Regex(@"^[0-9].");
如何使用'decimal.Parse'而不是正則文化設置的正則表達式?正則表達式不是這種情況下的最佳方式。 –
而不是正則表達式嘗試將輸入值實際轉換爲「decimal」。如果失敗 - 顯示紅色邊框。 – Sinatr
@SonerGönül更好'decimal.TryParse'。 – juharr