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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With