Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows phone 7 Handling backspace KeyDown event

I have a textbox in XAML:

<TextBox Text="blah" 
         Name="blah" 
         LostFocus="blah_OnLostFocus" 
         KeyDown="blah_OnKeyDown"/>

.cs file has the following event declared:

    private void blah_OnKeyDown(object sender, KeyEventArgs e)
    {
        TextBox t = sender as TextBox;
        int i = 0;
        if(e.Key == Key.Delete)
            i = 1;
    }

When I press the backspace key on the emulator's keyboard, the event is ignored. If I press any other button, it is triggered. Also, when I use the same event body for the KeyUp event, backspace key triggers it.

How do I track when the backspace key was pressed for KeyDown event? Why is pressing the backspace key does not trigger the KeyDown event?

Thank you.

like image 442
Eugene Avatar asked May 08 '11 05:05

Eugene


2 Answers

The backspace button is handled internally by the textbox control. The control will take the backspace event and remove a letter and won't bubble up the event to your event. This is by design. You'll notice that if there are no letters in the textbox, then the event is bubbled up. In order to get around this, you can use AddHandler to handle the event. Try doing this:

//Handle the mainpage loaded event and add the handler to the textbox
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    textBox1.AddHandler(TextBox.KeyDownEvent, new KeyEventHandler(blah_KeyDown), true);
}

Then change your Key_Down event handler to this:

private void blah_OnKeyDown(object sender, KeyEventArgs e)
{
    TextBox t = sender as TextBox;
    int i = 0;
    if(e.Key == Key.Back)
            i = 1;
}

That should have the textbox internally handle the event, but also call your OnKeyDown event.

like image 61
keyboardP Avatar answered Oct 21 '22 12:10

keyboardP


To detect backspace, you need to use Key.Back rather than Key.Delete

See Key enumeration at http://msdn.microsoft.com/en-us/library/system.windows.input.key(v=VS.95).aspx

like image 1
Stuart Avatar answered Oct 21 '22 11:10

Stuart