How to create a numeric textbox in Silverlight?

Mark Ingram picture Mark Ingram · Nov 6, 2008 · Viewed 27.2k times · Source

As the title says really. I've had a look at inheriting from TextBox, but the only sensible override was "OnKeyDown", but that just gives me a key from the Key enum (with no way to use Char.IsNumeric()).

Answer

amurra picture amurra · Nov 4, 2010

I took Nidhal's suggested answer and edited it a bit to handle the shift case for the characters above the digits (ie. !@#$%^&*()) since that solution will still allow those characters in the textbox.

private void NumClient_KeyDown(object sender, KeyEventArgs e)
{       
    // Handle Shift case
    if (Keyboard.Modifiers == ModifierKeys.Shift)
    {
       e.Handled = true;
    }

    // Handle all other cases
    if (!e.Handled && (e.Key < Key.D0 || e.Key > Key.D9))
    {
        if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
        {
            if (e.Key != Key.Back)
            {
                e.Handled = true;
            }
        }
    }           
}