将箭头键从TextBox重定向到ListBox

时间:2013-04-10 23:19:00

标签: wpf

我有一个带有ListView的TextBox,当TextBox具有焦点时,我想将向上和向下箭头键重定向到ListView。在我临时做任何事情之前,有人知道在控件之间重定向键的方法吗?

1 个答案:

答案 0 :(得分:0)

理想情况下,您可以设置KeyboardNavigation.DirectionalNavigation(http://msdn.microsoft.com/en-us/library/system.windows.input.keyboardnavigation.directionalnavigation.aspx),但我认为由于文本框处理方向键的方式,这将被忽略。

作为替代方案,您可以处理PreviewKeyDown以使向上和向下箭头模拟标签。

    <StackPanel PreviewKeyDown="StackPanel_PreviewKeyDown"  >
        <TextBox Text="Test" TabIndex="0" />
        <ListView TabIndex="1">
            <ListViewItem>One</ListViewItem>
            <ListViewItem>Two</ListViewItem>
            <ListViewItem>Three</ListViewItem>
        </ListView>
    </StackPanel>

    private void StackPanel_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        switch (e.Key)
        {
            case Key.Up:

                ((UIElement)Keyboard.FocusedElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
                e.Handled = true;

                break;
            case Key.Down:
                ((UIElement)Keyboard.FocusedElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                e.Handled = true;

                break;
        }
    }