Using the focus () method directly in the lostfocus event of textbox in WPF will cause an endless loop.
There are two methods for correct use:
Method 1:
Private Void Textbox3_lostfocus ( Object Sender, routedeventargs E)
{
If (Textbox3.text ! = " ABC " )
{
This . Dispatcher. begininvoke (system. Windows. Threading. dispatcherpriority. Render,
New Action (() =>
{
Textbox3.focus ();
}));
}
}
Method 2: Use the lostkeyboardfocus method:
Private Void Textbox3_lostkeyboardfocus ( Object Sender, keyboardfocuschangedeventargs E)
{
If (Textbox3.text ! = " ABC " )
{
Textbox3.focus ();
}
}
Note: you can find the following on msdn:
Lostkeyboardfocus
Occurs when the keyboard focus is no longer on this element
Lostfocus
This element occurs when the logical focus is lost.
Isfocused
Gets a value that determines whether the element has a logical focus.
Focus
Try to set the focus to this element
If both the keyboard focus and logical focus are set to this element True; If only the logical focus is set to this element or the focus is not forcibly changed for this method call False
Note:
In WPF, there are two main concepts related to focus: keyboard focus and logical focus.
Keyboard focus refers to the elements that receive keyboard input, while logical focus refers to the elements with focus in the focus range.
Elements with keyboard focus will also have logical focus, but those with logical focus may not necessarily have keyboard focus.
Keyboard focus refers to the element currently receiving keyboard input. Only one element with keyboard focus is allowed on the entire desktop.
The logical focus refers to the focusmanager. focusedelement in the focus range.
The Focus range is an element that tracks the focusedelement in its range.
When the keyboard focus is out of the Focus range, the focus element loses the keyboard focus, but retains the logical focus. When the keyboard focus is returned to the Focus range, the focus element gets the keyboard focus again.
As mentioned above, when we leave an applicationProgramSwitch to another input application, so our program will lose the keyboard focus and keep the logic focus
When you switch back, you can obtain the keyboard focus again.
In this way, we recommend that you use the first method to solve the problem, which can reduce the fearless verification of losing the keyboard focus when the program is switched.