It is important to mention that a textbox catches both the mouse and the keyboard events, so in order to move or remove the focus from a text box you have to release these 2 elements.
Let's start with the keyboard, Keyboard.ClearFocus();
will remove the keyboard focus from the textbox, and it's great for hiding the blinking cursor, but won't move the focus from the textbox, in other words the textbox will remain as focused element but without displaying the cursor.
You can check that by printing FocusManager.GetFocusedElement(this);
after Keyboard.ClearFocus();
.
So, if you have a LostFocus
event attached to the textbox or similar event, it will not be triggered because the element has not yet lost focus.
PreviewMouseDown += (s, e) => FocusManager.SetFocusedElement(this, null);
PreviewMouseDown += (s, e) => Keyboard.ClearFocus();
As a solution, you should set the Window focused element to null, by calling:
System.Windows.Input.FocusManager.SetFocusedElement(this, null);
Now if you are wondering if we can get rid of the Keyboard.ClearFocus();
then the answer is no, because we are going to remove the mouse focus, but the keyboard focus will still be there. (you will notice the blinking cursor which is still there, and you will be able to type some text in the textbox).
LostFocus
event, but another focusable element (e.g. another text box), it will. – Louiselouisette