在TextBox中检索插入符的结束位置,以将Caret放在下一个TextBox中

时间:2010-10-07 13:08:24

标签: wpf textbox position caret

如何在WPF文本框中找到Caret的最终位置,这样我就不能再使用插入符号向右移动了?

1 个答案:

答案 0 :(得分:1)

如果您需要找到CaretIndex,请查看以下question

但是,如果您希望在某些条件下跳转到下一个TextBox,请查看以下示例。在这里,我使用TextBox属性MaxLength和KeyUp事件在完成一个TextBox时跳转到下一个TextBox。

这是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();
      }
   }
}

修改
阅读以下answer后,我修改了TextBox_KeyUp,如下所示:

  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);
     }
  }
}