1

キャレットで右に移動できないように、WPF テキストボックスでキャレットの終了位置を見つけるにはどうすればよいですか?

4

1 に答える 1

1

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);
     }
  }
}
于 2010-10-07T16:27:12.760 に答える