5

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.

2 Answers 2

6

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.

2
  • As an extension to this answer, see this post on Silverlght forums forums.silverlight.net/forums/p/83981/217568.aspx
    – Stuart
    May 8, 2011 at 18:49
  • This worked, I only had to put the textBox1.AddHandler... statement into the page constructor, but then event seemed to have been triggered twice. It is ok though, thank you for the interesting piece of info about backspace key not bubbling up unless the textbox is empty, I like that behavior. For those who still need to control each backspace key press, KeyUp event is working just fine for that purpose.
    – Eugene
    May 9, 2011 at 13:04
1

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

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.
    – Eugene
    May 8, 2011 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.