我目前正在开发一个WPF应用程序,我想要一个TextBox
只能输入数字。我知道当失去焦点时可以验证其内容并阻止内容为数字,但在其他Windows表单应用程序中,我们通常会完全阻止除数字以外的任何输入。此外,我们会将该代码放在单独的dll中以便在多个地方引用。
以下是2008年没有使用WPF的代码:
Public Shared Sub BloquerInt(ByRef e As System.Windows.Forms.KeyPressEventArgs, ByRef oTxt As Windows.Forms.TextBox, ByVal intlongueur As Integer)
Dim intLongueurSelect As Integer = oTxt.SelectionLength
Dim intPosCurseur As Integer = oTxt.SelectionStart
Dim strValeurTxtBox As String = oTxt.Text.Substring(0, intPosCurseur) & oTxt.Text.Substring(intPosCurseur + intLongueurSelect, oTxt.Text.Length - intPosCurseur - intLongueurSelect)
If IsNumeric(e.KeyChar) OrElse _
Microsoft.VisualBasic.Asc(e.KeyChar) = System.Windows.Forms.Keys.Back Then
If Microsoft.VisualBasic.AscW(e.KeyChar) = System.Windows.Forms.Keys.Back Then
e.Handled = False
ElseIf strValeurTxtBox.Length < intlongueur Then
e.Handled = False
Else
e.Handled = True
End If
Else
e.Handled = True
End If
在WPF中有没有对应的方式?如果是在样式中也没关系,但我刚接触WPF,对样式的了解还不够充分。
if (e.Text.Any(ch => !Char.IsDigit(ch))) e.Handled = true;
- Paw Baltzersen