VB.net: 只允许数字,复制粘贴回去 space 在 WPF 中删除?

VB.net: Only allow digits, copy paste back space delete in WPF?

如何只允许数字,不允许. , -,并在文本框中复制粘贴Ctrl C + Ctrl V, backspace and delete在VB.netWPF

由于是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