Извлечете крайната позиция на каретката в текстовото поле, за да поставите каретката в следващото текстово поле

Как да намеря крайната позиция на каретката в текстово поле на WPF, така че да не мога повече да се движа надясно с каретката?


person Pascal    schedule 07.10.2010    source източник


Отговори (1)


Ако трябва да намерите CaretIndex, вижте следното въпрос.

Въпреки това, ако искате да преминете към следващото TextBox при определени условия, вижте следната проба. Тук използвам свойството MaxLength на TextBox и събитието 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);
     }
  }
}
person Zamboni    schedule 07.10.2010
comment
Хей Zamboni, вашият код Action... е хубав. Това анонимни методи ли са? - person Pascal; 18.10.2010