I have a Grid which contains like few TextBoxes below each other :
By pressing Enter I need to jump from txt1 to txt2, from txt2 to txt3 and so on, and I solved it like this:
private void Grid_PreviewKeyDown_1(object sender, KeyEventArgs e)
{
try
{
if (e.Key == Key.Enter)
{
UIElement element = e.Source as UIElement;
element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
//e.Handled = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And my issue is here, on each of txt boxes by pressing Enter I should calculate something from another txtBoxes, and when I press enter on txt1 it is gonna jump on txt2 and immediatelly call txt2_KeyDown
event, which I want to avoid.. I want to call txt2_KeyDown
event when I'm 'standing' on txt2 and when I press enter..
ie:
private void txt2_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
try
{
CalculateSomethingFromOtherTextBoxes();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
This above is being fired when I am 'standing' on txt1 and when I want to jump to txt2 by pressing Enter, how can I just 'jump' without calling txt2 KeyDown event If I did not press Enter while I am really 'standing' on 'txt2'.
Thanks guys, Cheers
The problem is because of a KeyDown
event that you attached to textboxes.
Instead, remove this event and add PreviewKeyDown
event.
So, your method signature should be something like this:
private void txt2_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
try
{
CalculateSomethingFromOtherTextBoxes();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
I tested it and it is working as expected.
And my issue is here, on each of txt boxes by pressing Enter I should calculate something from another txtBoxes, and when I press enter on txt1 it is gonna jump on txt2 and immediatelly call txt2_KeyDown event, which I want to avoid.. I want to call txt2_KeyDown event when I'm 'standing' on txt2 and when I press enter..
Then you could handle the LostKeyboardFocus
event of "txt2" instead of handling the KeyDown
event:
private Key key;
private void Grid_PreviewKeyDown(object sender, KeyEventArgs e)
{
key = e.Key;
if (key == Key.Enter)
{
UIElement element = e.OriginalSource as UIElement;
element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
private void txt2_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (key == Key.Enter)
{
CalculateSomethingFromOtherTextBoxes();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.