Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop a WPF Textbox from losing focus

Tags:

focus

wpf

textbox

I have a WPF Textbox, that I want to check that the text value is correct before I allow it to lose keyboard/focus.

I have tried setting e.Handled in the InputBox_LostFocus & InputBox_LostKeyboardFocus events, but it doesnt seem to be achieving what I want.

Any suggestions on how I can lock focus to a Textbox?

like image 341
Mark Pearl Avatar asked Feb 06 '10 11:02

Mark Pearl


2 Answers

The best way to do this is to handle the PreviewLostKeyboardFocus event which is fired while the event is tunneling down to your textbox. Set handle to true and nothing else will receive the notification (meaning focus will not be transfered away from your textbox). Hope this helps.

like image 105
Jerod Edward Moemeka Avatar answered Sep 27 '22 16:09

Jerod Edward Moemeka


You can call Mouse.Capture on a UIElement. This will then give you every mouse event that hapens whether on the element or not. but its tricky to use. You can capture the mouse on your text box and register for lost capture events, when you lose capture you can recapture. you have to watch out for strange behaviors. Generally its bad practice (I think) to not allow a user to move off a field. what is better is to allow them to do whatever they want, but disable the button that they push after entering data until all fields are valid (or something similar)

Here are some links

other SO question

msdn sample code

the combo box uses mouse capture to tell if the user has clicked elsewhere in the app to close the combo box if its open if you click on another control (or outside the window)

I dont know if this technique will stop you tabbing off the element. there are two kinds of focus in a wpf app. You have logical focus and keyboard focus. Multiple elements can have logical focus at once (each within a focus scope). think for example a textbox can have logical focus while you are clicking a menu (which has logical focus as well). Keyboard focus can only be in one place at a time. You are going to make a lot of work for yourself. I would seriously consider if you are doing your interaction in the right way. You could spend days getting this interaction correct. If you stop your textbox losing focus, what happens if the user clicks the close button?

heres the msdn article on focus

like image 24
Aran Mulholland Avatar answered Sep 27 '22 18:09

Aran Mulholland