WPF 回车转Tab实现跳转

1.重写窗体的KeyDown事件

Code Snippet
  1. protected override void OnKeyDown(KeyEventArgs e)
  2. {
  3.     if (e.Key == Key.Enter)
  4.     {
  5.         // MoveFocus takes a TraveralReqest as its argument.
  6.         TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
  7.  
  8.         // Gets the element with keyboard focus.
  9.         UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
  10.  
  11.         // Change keyboard focus.
  12.         if (elementWithFocus != null)
  13.         {
  14.             elementWithFocus.MoveFocus(request);
  15.         }
  16.         e.Handled = true;
  17.     }
  18.     base.OnKeyDown(e);
  19. }

2.在基容器如Grid的KeyDown事件中

Code Snippet
  1. <Grid KeyDown="Grid_KeyDown">

实现代码

Code Snippet
  1. private void Grid_KeyDown(object sender, KeyEventArgs e)
  2. {
  3.     var uie = e.OriginalSource as UIElement;
  4.     if (e.Key == Key.Enter)
  5.     {
  6.         uie.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
  7.         e.Handled = true;
  8.     }
  9. }
posted @ 2010-01-29 13:18  流泉飞石  阅读(2662)  评论(3编辑  收藏  举报