[英]VB.net: Only allow digits, copy paste back space delete in WPF?
我怎么只允許數字,不. , -
. , -
, 以及在 VB.net WPF的文本框中復制粘貼Ctrl C + Ctrl V, backspace and delete
?
由於它是 WPF,擊鍵和按鍵不起作用。 我不知道解決這個問題。
我似乎無法為此找到解決方案,如果沒有這個,每次有人輸入數字以外的任何內容時,我的程序都會中斷。 請幫忙!
在這種情況下,我傾向於使用 VB 工具箱中的 numericUpDown 控件。 它只接受數字值,並有一些方便的按鈕來增加或減少值。 此外,您可以設置最小值和最大值。
哦,我找到了答案,只需包含此功能。
Protected Overrides Sub OnPreviewTextInput(e As
System.Windows.Input.TextCompositionEventArgs)
e.Handled = Not AreAllValidNumericChars(e.Text)
MyBase.OnPreviewTextInput(e)
End Sub
Private Function AreAllValidNumericChars(str As String) As Boolean
For Each c As Char In str
If Not [Char].IsNumber(c) Then
Return False
End If
Next
Return True
End Function`
這個簡單的代碼將幫助您將數字僅用於 VB.net WPF 上的文本框
Private Sub txtTextBox_PreviewKeyDown(sender As Object, e As KeyRoutedEventArgs) Handles txtTextBox.PreviewKeyDown
If e.Key <> 8 Then
'48 - 57 = Ascii codes for numeric only
If e.Key < 48 Or e.Key > 57 Then
e.Handled = True
End If
End If
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.