1.重写窗体的KeyDown事件
Code Snippet
- protected override void OnKeyDown(KeyEventArgs e)
- {
- if (e.Key == Key.Enter)
- {
- // MoveFocus takes a TraveralReqest as its argument.
- TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
- // Gets the element with keyboard focus.
- UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
- // Change keyboard focus.
- if (elementWithFocus != null)
- {
- elementWithFocus.MoveFocus(request);
- }
- e.Handled = true;
- }
- base.OnKeyDown(e);
- }
2.在基容器如Grid的KeyDown事件中
Code Snippet
- <Grid KeyDown="Grid_KeyDown">
实现代码
Code Snippet
- private void Grid_KeyDown(object sender, KeyEventArgs e)
- {
- var uie = e.OriginalSource as UIElement;
- if (e.Key == Key.Enter)
- {
- uie.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
- e.Handled = true;
- }
- }
本文介绍了如何在WPF应用程序中通过重写窗体的KeyDown事件来实现键盘焦点的自动切换,包括两种实现方法:一种是在窗体级别进行重写,另一种是在基容器如Grid的KeyDown事件中实现。
943

被折叠的 条评论
为什么被折叠?



