I want to implement such feature: In a barcode text box, when a "=" key (or "+" key) is pressed, the "=" (or "+") character will not append to barcode textbox, and program will use textbox text as barcode to search product item.
To achieve this effect, we need use handle PreviewKeyDown event. Listening for KeyDown event is not working here, because when KeyDown event is fired, the new character is already appended to the textbox. (PreviewKeyDown is a tunneling event and KeyDown is a bubbling event)
1 2 3 4 5 6 7 8 |
private async void BarcodeTextBox_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.OemPlus || e.Key == Key.Add) { e.Handled = true; await AddItemToCartByBarcode(BarcodeTextBox.Text); } } |
But when I pressed "=" key, the PreviewKeyDown event is triggered multiple times.
By debugging I found only one event's IsDown property is true, while other triggered events' IsDown property is false and their IsUp property is true. To fix this solution we can check whether e.IsDown is true.
1 2 3 4 5 |
if ((e.Key == Key.OemPlus || e.Key == Key.Add) && e.IsDown == true) { e.Handled = true; await AddItemToCartByBarcode(BarcodeTextBox.Text); } |