1
votes

I want to design a numeric textbox in silverlight.

I have added keydown event of TextBox to handle the keypress.

Inside event I validate the key entered in the textbox.

event as follows

  private void TextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (!this.Validate(sender,e))
            e.Handled = true;
    }

function Validate as follows

  private bool Validate(object sender, KeyEventArgs e)
    {

        if (e.Key == Key.Enter) //accept enter and tab
        {
            return true;
        }
        if (e.Key == Key.Tab)
        {
            return true;
        }

        if (e.Key < Key.D0 || e.Key > Key.D9) //accept number on alphnumeric key
            if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9) //accept number fomr NumPad
                if (e.Key != Key.Back) //accept backspace
                    return false;

        return true;
    }

I am not able to detect shift and Key.D0 to Key.D1 i.e.

SHIFT + 1 which returns "!"

SHIFT + 3 returns "#" like wise any other special keys.

I dont want user to enter special character in to textbox.

How do i handle this keys event??

3

3 Answers

6
votes

In Silverlight, I don't think there are any Modifiers in the KeyEventArgs class but instead in Keyboard:

    public void KeyDown(KeyEventArgs e)
    {
        if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.D0)
        {
            ControlZero();
        }
    }
0
votes

e should have a property on it that will tell you if Shift, Control or Alt are pressed. e.Modifiers can also give you additional information about which additional modifier keys have been pressed.

To cancel the character you can set e.Handled to True, which will cause the control to ignore the keypress.

0
votes
textBox2.Text = string.Empty;
textBox2.Text = e.Modifiers.ToString() + " + " + e.KeyCode.ToString();