Технически это неправильно, так как вы пометили свой вопрос WPF.Но так как вы приняли другой ответ Windows Forms, я опубликую свое решение, которое работает для действительных чисел, а не целых чисел.Он также локализован, чтобы принимать только десятичный разделитель текущей локали.
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;
}