Enter-to-Tab in WPF

本文介绍如何在WPF应用程序中实现使用Enter键代替Tab键进行焦点切换的方法。通过处理PreviewKeyDown事件并调用MoveFocus方法,可以轻松地使Enter键在不同控件间导航。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Enter-to-Tab in WPF

Like many users of line-of-business applications, my own users just can't understand the Tab key. For them, pressing Enter on the keyboard shouldn't submit a form, it should just move their focus to the next control.

Back in the Windows Forms days there was a neat way to achieve this functionality: You caught the KeyDown event on each of your controls and used the SelectNextControl method to move focus to the next control. In WPF, however, there's no SelectNextControl method! So how do we do something similar?

The first trick to use in WPF is to handle the PreviewKeyDown event on all your data-entry controls in one hit, rather than having to declaratively handle it individually in each control. In my case I have all my controls inside a grid, so I simply declare my grid like this:

<Grid UIElement.PreviewKeyDown="Grid_PreviewKeyDown">

What I'm doing here is telling the grid that any child control that descends from UIElement (and that includes TextBoxes and ComboBoxes) should have their PreviewKeyDown event handled by a common method called Grid_PreviewKeyDown.

So now we have caught key presses on our controls. Now, how do we tell the window to move its focus to the next available control? We don't have SelectNextControl, but we have a new method with a similar function: MoveFocus!

private void Grid_PreviewKeyDown(object sender, KeyEventArgs e)
{
 var uie = e.OriginalSource as UIElement;

 if (e.Key == Key.Enter)
 {
 e.Handled = true;
 uie.MoveFocus(
 new TraversalRequest(
 FocusNavigationDirection.Next));
 }
}

So here we're getting the control that sent us the PreviewKeyDown event, and calling its MoveFocus method to shift the focus to the next control!

So now you have no excuses! WPF can be used for line-of-business style applications after all!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值