Về mặt kỹ thuật này là sai vì bạn gắn thẻ câu hỏi của bạn WPF. Nhưng kể từ khi bạn chấp nhận câu trả lời Windows Forms khác, tôi sẽ đăng giải pháp của tôi mà làm việc cho số thực hơn là số nguyên. Nó cũng được bản địa hóa để chỉ chấp nhận dấu phân cách thập phân của ngôn ngữ hiện tại.
private void doubleTextBox_KeyPress (object sender, KeyPressEventArgs e)
{
var textBox = sender as TextBoxBase;
if (textBox == null)
return;
// did the user press their locale's decimal separator?
if (e.KeyChar.ToString() == CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)
{
if (textBox.Text.Length == 0) // if empty, prefix the decimal with a 0
{
textBox.Text = "0" + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
e.Handled = true;
textBox.SelectionStart = textBox.TextLength;
}
// ignore extra decimal separators
else if (textBox.Text.Contains(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator))
e.Handled = true;
}
// allow backspaces, but no other non-numeric characters;
// note that arrow keys, delete, home, end, etc. do not trigger KeyPress
else if (e.KeyChar != '\b' && (e.KeyChar < '0' || e.KeyChar > '9'))
e.Handled = true;
}
Nguồn
2015-06-09 15:01:21
Đối với WPF, bạn có thể cần phải tham khảo trang này: http://stackoverflow.com/questions/481059/where-can-i-find-a-free-masked-textbox-in-wpf – Vlad