I have the following visual tree:
<DockPanel>
<TextBox Name="ElementWithFocus" DockPanel.Dock="Left" />
<ListBox DockPanel.Dock="Left" Width="200" KeyUp="handleListBoxKeyUp">
<ListBoxItem>1</ListBoxItem>
<ListBoxItem>4</ListBoxItem>
<ListBoxItem>3</ListBoxItem>
<ListBoxItem>2</ListBoxItem>
</ListBox>
<TextBox DockPanel.Dock="Left" />
</DockPanel>
handleListBoxKeyUp is the following:
private void handleListBoxKeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
((UIElement)sender).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
When the ListBox has keyboard focus (really a ListBoxItem I’d guess), pressing Enter moves the focus to the first item in the ListBox instead of to the following TextBox. Why is this happening and how can I get the Enter key to act like Tab here?
Rather than calling
MoveFocuson the sender, you should call it on the original source found in the event args.The
senderparameter will always be theListBoxitself, and callingMoveFocuson that withFocusNavigationDirection.Nextwill go to the next control in the tree, which is the firstListBoxItem.The original source of the routed event will be the selected
ListBoxItem, and the next control after that is theTextBoxthat you want to receive focus.