How do I find the end position of the Caret in a WPF textbox so I can`t move right anymore with the caret?
views:
43answers:
1
+1
Q:
[WPF] Retrieve the End position of the Caret in the TextBox to put the Caret in the next TextBox
A:
If you need to find the CaretIndex look at the following question.
However, if you are looking to jump to the next TextBox under certain conditions check out the following sample. Here I use the TextBox property MaxLength and the KeyUp event to jump to the next TextBox when one is completed.
Here is the 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>
Here is the KeyUp event from the code-behind:
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();
}
}
}
Edit:
After reading the following answer I modified the TextBox_KeyUp as follows:
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);
}
}
}
Zamboni
2010-10-07 16:27:12
Hey Zamboni, your code Action... is nice. Are these anonymous methods?
Pascal
2010-10-18 18:32:53