这个问题已经在这里有一个答案:
- 我如何获得一个TextBox只接受在WPF数字输入? 28个回答
我想创建一个文本框只接受数字值,在特定的范围内。 什么是实现这样的TextBox的最佳方式?
我想过获得TextBox和覆盖TextProperty的验证和胁迫。 但是,我不知道如何做到这一点,据我所知,得出WPF控件一般不推荐。
编辑:
我需要的是一个非常基本的文本过滤掉哪些不是所有的数字按键。 实现这一目标最简单的方法是处理TextBox.PreviewTextInput事件:
private void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
int result;
if (!validateStringAsNumber(e.Text,out result,false))
{
e.Handled = true;
}
}
(validateStringAsNumber是我的函数,它主要使用Int.TryParse)
一些建议的解决方案的可能会更好,但对于简单的功能,我需要这个解决方案是最简单快捷的同时,充分实现我的需要。
到目前为止,我所看到的大多数实现使用PreviewTextInput事件来实现正确的面具行为。 这一个从TextBox继承和这一个使用附加属性。 两者都使用NET的MaskedTextProvider提供正确的面具的行为,但如果你只是想要一个简单的“数字只有”文本框,你不需要这个类。
private void txt_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = sender as TextBox;
int iValue = -1;
if (Int32.TryParse(textBox.Text, out iValue) == false)
{
TextChange textChange = e.Changes.ElementAt<TextChange>(0);
int iAddedLength = textChange.AddedLength;
int iOffset = textChange.Offset;
textBox.Text = textBox.Text.Remove(iOffset, iAddedLength);
}
}
依我拙见,以满足这一要求的最好方法是使用只OnTextChanged
事件,因为它能够处理从按键的数字上,还能够处理复制+从剪贴板粘贴了。 我希望,如下图所示我的VB代码可以扔在这一些轻。
Private Sub NumericBox_TextChanged(sender As Object, e As TextChangedEventArgs) Handles Me.TextChanged
Dim Buffer As New StringBuilder
Dim Index As Integer = Me.SelectionStart
For Each C In Me.Text
If Char.IsDigit(C) Then
Buffer.Append(C)
ElseIf Me.SelectionStart > Buffer.Length Then
Index -= 1
End If
Next
Me.Text = Buffer.ToString
Me.SelectionStart = Index
End Sub
整体最好的,为什么是使用替代方法OnKeyPressed
像文本框。 下面是使用静态方法夏亚的覆盖码IsDigit
。
if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar)) e.Handled = true;
这就是你真正需要做的。
这将是我的首选方法:
private void yearTxt_PreviewKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.D0:
case Key.D1:
case Key.D2:
case Key.D3:
case Key.D4:
case Key.D5:
case Key.D6:
case Key.D7:
case Key.D8:
case Key.D9:
case Key.NumLock:
case Key.NumPad0:
case Key.NumPad1:
case Key.NumPad2:
case Key.NumPad3:
case Key.NumPad4:
case Key.NumPad5:
case Key.NumPad6:
case Key.NumPad7:
case Key.NumPad8:
case Key.NumPad9:
case Key.Back:
break;
default:
e.Handled = true;
break;
}
}