简体   繁体   中英

Textbox LostFocus event handling

I have a LostFocus Event on my textbox, but usually when pressing the Tab key what happens is, the "LostFocus" event triggers, and the next control gets focus. i want to keep focus on the textbox (Assuming an input error happened) instead of moving focus to the next control.

i've tried setting the e event to handled, but nothing changed.

private void phone(object sender, RoutedEventArgs e)
{
    TextBox text = (sender as TextBox);
    if (text.Text == "") return;
    else if (text.Text.Length > 10 || text.Text.Length < 10)
    {
        MessageBox.Show("Valid Input");
        select(sender);
    }
}

This is the event i'm trying to use, but as i said, the focus moves to the next control (which is wrong).

It's a logical focus change and not a keyboard focus change.See UIElement.LostFocus Event for more information.

You should try setting focus to your textbox like below (assuming txt1 is the id of your textbox)

txt1.Focusable = true;
Keyboard.Focus(txt1);

You should use the KeyPressed event! This way, when your textbox has focus and the user enters a key, you can check if it's the tab key. If it is the tab key, you simple give your textbox focus again. More info here: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=vs.110).aspx

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM