Create WPF TextBox that accepts only numbers
This question already has an answer here:
Most implementations I have seen so far are using the PreviewTextInput event to implement the correct mask behavior. This one inherits from TextBox and this one uses attached properties. Both use .Net's MaskedTextProvider to provide the correct mask behaviour, but if you just want a simple 'numbers only' textbox you don't need this class.
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);
}
}
In my humble opinion, the best way to fulfill this requirement is using only OnTextChanged
event because it can handle the digit from keystroke and also be able to handle Copy+Paste from clipboard too. I hope that my VB code shown below can throw some light on this.
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
链接地址: http://www.djcxy.com/p/95962.html
上一篇: 动态(C#4)和var之间有什么区别?
下一篇: 创建只接受数字的WPF文本框