WPF - Remove focus when clicking outside of a textbox

前端 未结 13 2156
粉色の甜心
粉色の甜心 2020-12-02 19:11

I have some textboxes where I would like focus to behave a little differently than normal for a WPF application. Basically, I would like them to behave more like a textbox b

13条回答
  •  旧巷少年郎
    2020-12-02 19:17

    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).

提交回复
热议问题