简体   繁体   English

文本框LostFocus事件处理

[英]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. 我的文本框上有一个LostFocus事件,但是通常在按Tab键时会发生什么,“ LostFocus”事件将触发,下一个控件将获得焦点。 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. 我尝试将e事件设置为已处理,但没有任何更改。

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. 这是逻辑上的焦点更改,而不是键盘上的焦点更改。有关更多信息,请参见UIElement.LostFocus事件

You should try setting focus to your textbox like below (assuming txt1 is the id of your textbox) 您应该尝试将焦点设置为文本框,如下所示(假设txt1是文本框的ID)

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

You should use the KeyPressed event! 您应该使用KeyPressed事件! This way, when your textbox has focus and the user enters a key, you can check if it's the tab key. 这样,当您的文本框具有焦点并且用户输入键时,您可以检查它是否为Tab键。 If it is the tab key, you simple give your textbox focus again. 如果它是Tab键,则只需简单地再次指定文本框焦点即可。 More info here: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=vs.110).aspx 此处的更多信息: https : //msdn.microsoft.com/zh-cn/library/system.windows.forms.control.keypress(v=vs.110).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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