2013-07-12 23 views

Trả lời

5

Bạn có thể xử lý các KeyDown/KeyUp sự kiện trên textbox của bạn (tùy thuộc vào việc bạn muốn đi đến tiếp theo ở đầu hoặc cuối của báo chí key).

Ví dụ XAML:

<TextBox KeyUp="TextBox_KeyUp" /> 

Mã Đằng sau:

private void TextBox_KeyUp(object sender, KeyRoutedEventArgs e) 
    { 
     TextBox tbSender = (TextBox)sender; 

     if (e.Key == Windows.System.VirtualKey.Enter) 
     { 
      // Get the next TextBox and focus it. 

      DependencyObject nextSibling = GetNextSiblingInVisualTree(tbSender); 
      if (nextSibling is Control) 
      { 
       // Transfer "keyboard" focus to the target element. 
       ((Control)nextSibling).Focus(FocusState.Keyboard); 
      } 
     } 
    } 

Toàn mã ví dụ bao gồm cả mã cho GetNextSiblingInVisualTree (phương pháp helper): https://github.com/finnigantime/Samples/tree/master/examples/Win8Xaml/TextBox_EnterMovesFocusToNextControl

Lưu ý rằng gọi Focus() với FocusState.Keyboard hiển thị tiêu điểm chấm xung quanh các yếu tố có một rect trong mẫu kiểm soát của chúng (e. g. Nút). Gọi Focus() với FocusState.Pointer không hiển thị tiêu điểm rect (bạn đang sử dụng touch/mouse, vì vậy bạn biết bạn đang tương tác với phần tử nào).

+0

Cảm ơn Patrick. Nó hoạt động một điều trị. – Sun

1

Tôi đã cải thiện một chút đối với chức năng "GetNextSiblingInVisualTree". Phiên bản này tìm kiếm TextBox tiếp theo thay vì đối tượng tiếp theo.

private static DependencyObject GetNextSiblingInVisualTree(DependencyObject origin) 
    { 
     DependencyObject parent = VisualTreeHelper.GetParent(origin); 

     if (parent != null) 
     { 
      int childIndex = -1; 
      for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); ++i) 
      { 
       if (origin == VisualTreeHelper.GetChild(parent, i)) 
       { 
        childIndex = i; 
        break; 
       } 
      } 

      for (int nextIndex = childIndex + 1; nextIndex < VisualTreeHelper.GetChildrenCount(parent); nextIndex++) 
      { 
       DependencyObject currentObject = VisualTreeHelper.GetChild(parent, nextIndex); 

       if(currentObject.GetType() == typeof(TextBox)) 
       { 
        return currentObject; 
       } 
      } 
     } 

     return null; 
    } 
Các vấn đề liên quan