7
votes

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?

2
Focus-locking makes for a really hateful user experience. Before I spent a lot of effort trying to figure out how to do this, I'd redesign the UI to work differently - say, disable every other control in the window until the TextBox has valid content.Robert Rossney
@Robert: Unless you're designing a cash register application, then it is practically mandatory. In a register app, you type in a number or text, THEN decide what that input actually is, by hitting a button. (e.g. Number then SKU, number then quantity, number then payment key, etc.)HiredMind

2 Answers

9
votes

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.

4
votes

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