Técnicamente esto es incorrecto ya ha etiquetado su pregunta WPF. Pero como aceptó la otra respuesta de Windows Forms, publicaré mi solución que funciona para números reales en lugar de enteros. También está localizado para aceptar solo el separador decimal del lugar actual.
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;
}
para WPF, que tal vez tendría que consultar esta página: http://stackoverflow.com/questions/481059/where-can-i-find-a-free-masked-textbox-in-wpf – Vlad