Handling Focus in WPF
On my WPF course someone asked how we could move the focus to the next control on the page when the enter key is pressed on a textbox. Let’s suppose we have a data entry form which mostly is consisted of TextBox (or alike) controls.
A lot of users are used to press enter when they are finished entering a field, but we need to change the focus to the next control when this happens so user won’t have to press tab key. Let’s see how this would be done in WinForms world. There are a couple of ways to tackle this:
Create a custom control, e.g. a custom TextBox derived control and listen to keydown event and move the focus to the next control then. Existing controls in your toolbelt also may provide this functionality out of the box. In fact, DevExpress controls have this feature and it is as easy as setting a property.
Create a Property Extender control and by setting the property on the control, we change the focus when the enter key is pressed. This is an elegant solution, but you also need to remember to set the property on all the controls.
In WPF world, things are a little different. With the power of “Preview” events, you can achieve this pretty easily by listening to the KeyDown event of your Window (or root object) instead of each Textboxes.
Notice the PreviewKeyDown event is on the Grid (root container) control and nothing is specified on TextBox controls. Moving the focus to another control is a little bit different compared to WinForms:
private void OnContainerKeyDown(object sender, KeyEventArgs e)