I have a windows 8 store application with numerous textboxes. When I press enter on the keyboard I'd like the focues to move to the next control.
How can I do this?
Thanks
You can handle the KeyDown/KeyUp events on your TextBoxes (depending on whether you want to go to the next one at the beginning or end of the key press).
Example XAML:
<TextBox KeyUp="TextBox_KeyUp" />
Code Behind:
private void TextBox_KeyUp(object sender, KeyRoutedEventArgs e)
{
TextBox tbSender = (TextBox)sender;
if (e.Key == Windows.System.VirtualKey.Enter)
{
// Get the next TextBox and focus it.
DependencyObject nextSibling = GetNextSiblingInVisualTree(tbSender);
if (nextSibling is Control)
{
// Transfer "keyboard" focus to the target element.
((Control)nextSibling).Focus(FocusState.Keyboard);
}
}
}
Full example code including code for the GetNextSiblingInVisualTree() helper method: https://github.com/finnigantime/Samples/tree/master/examples/Win8Xaml/TextBox_EnterMovesFocusToNextControl
Note that calling Focus() with FocusState.Keyboard shows the dotted focus rect around elements that have such a rect in their control template (e.g. Button). Calling Focus() with FocusState.Pointer does not show the focus rect (you are using touch/mouse, so you know which element you are interacting with).
I made a slight improvement to the "GetNextSiblingInVisualTree" function. This version searches for the next TextBox instead of the next object.
private static DependencyObject GetNextSiblingInVisualTree(DependencyObject origin)
{
DependencyObject parent = VisualTreeHelper.GetParent(origin);
if (parent != null)
{
int childIndex = -1;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); ++i)
{
if (origin == VisualTreeHelper.GetChild(parent, i))
{
childIndex = i;
break;
}
}
for (int nextIndex = childIndex + 1; nextIndex < VisualTreeHelper.GetChildrenCount(parent); nextIndex++ )
{
DependencyObject currentObject = VisualTreeHelper.GetChild(parent, nextIndex);
if( currentObject.GetType() == typeof(TextBox))
{
return currentObject;
}
}
}
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With