Why does UIElement.MoveFocus() not move the focus to the next sibling element in a ListBox?

爱⌒轻易说出口 提交于 2019-12-12 12:29:03

问题


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?


回答1:


Rather than calling MoveFocus on the sender, you should call it on the original source found in the event args.

The sender parameter will always be the ListBox itself, and calling MoveFocus on that with FocusNavigationDirection.Next will go to the next control in the tree, which is the first ListBoxItem.

The original source of the routed event will be the selected ListBoxItem, and the next control after that is the TextBox that you want to receive focus.

((UIElement)e.OriginalSource).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));



回答2:


Another method that gets the code to go to the next text box would be to raise the tab event manually. Replacing your code inside the if statement with the following worked for me:

KeyEventArgs args = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.Tab);
args.RoutedEvent = Keyboard.KeyDownEvent;
InputManager.Current.ProcessInput(args);


来源:https://stackoverflow.com/questions/14127577/why-does-uielement-movefocus-not-move-the-focus-to-the-next-sibling-element-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!