Получите конечную позицию каретки в TextBox, чтобы поместить каретку в следующий TextBox - PullRequest
1 голос
/ 07 октября 2010

Как найти конечную позицию каретки в текстовом поле WPF, чтобы я больше не мог двигаться вправо с кареткой?

1 Ответ

1 голос
/ 07 октября 2010

Если вам нужно найти CaretIndex, посмотрите на следующий вопрос .

Однако, если вы хотите перейти к следующему TextBox при определенных условиях, ознакомьтесь со следующим примером.Здесь я использую свойство TextBox MaxLength и событие KeyUp для перехода к следующему 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();
      }
   }
}

Редактировать:
Прочитав следующий ответ Я изменил 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);
     }
  }
}
...