2010-10-07 41 views

回答

1

如果您需要查找以下question的CaretIndex參數。

但是,如果您希望在某些條件下跳到下一個TextBox,請查看以下示例。這裏我使用TextBox屬性MaxLength和KeyUp事件來完成一個跳轉到下一個文本框。

這裏是XAML:

<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition/> 
     <RowDefinition/> 
    </Grid.RowDefinitions> 
    <StackPanel 
     Grid.Row="0"> 
     <TextBox Text="" MaxLength="3" KeyUp="TextBox_KeyUp" > 
     </TextBox> 
     <TextBox Text="" MaxLength="3" KeyUp="TextBox_KeyUp"> 
     </TextBox> 
     <TextBox Text="" MaxLength="4" KeyUp="TextBox_KeyUp"> 
     </TextBox> 
     </StackPanel> 
</Grid> 

下面是從代碼隱藏KeyUp事件:

private void TextBox_KeyUp(object sender, KeyEventArgs e) 
{ 
    TextBox tb = sender as TextBox; 
    if ((tb != null) && (tb.Text.Length >= tb.MaxLength)) 
    { 
     int nextIndex = 0; 
     var parent = VisualTreeHelper.GetParent(tb); 
     int items = VisualTreeHelper.GetChildrenCount(parent); 
     for(int index = 0; index < items; ++index) 
     { 
     TextBox child = VisualTreeHelper.GetChild(parent, index) as TextBox; 
     if ((child != null) && (child == tb)) 
     { 
      nextIndex = index + 1; 
      if (nextIndex >= items) nextIndex = 0; 
      break; 
     } 
     } 

     TextBox nextControl = VisualTreeHelper.GetChild(parent, nextIndex) as TextBox; 
     if (nextControl != null) 
     { 
     nextControl.Focus(); 
     } 
    } 
} 

編輯:
我修改TextBox_KeyUp作爲閱讀以下answer後如下:

private void TextBox_KeyUp(object sender, KeyEventArgs e) 
    { 
    Action<FocusNavigationDirection> moveFocus = focusDirection => 
    { 
     e.Handled = true; 
     var request = new TraversalRequest(focusDirection); 
     var focusedElement = Keyboard.FocusedElement as UIElement; 
     if (focusedElement != null) 
      focusedElement.MoveFocus(request); 
    }; 

    TextBox tb = sender as TextBox; 
    if ((tb != null) && (tb.Text.Length >= tb.MaxLength)) 
    { 
     moveFocus(FocusNavigationDirection.Next); 
    } 
    } 
} 
+0

嘿Zamboni,你的代碼Action ...很好。這些匿名方法是? – Pascal 2010-10-18 18:32:53

相關問題