wpf 使用箭头键导航列表框项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18448927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:30:14  来源:igfitidea点击:

Navigate listboxitems using arrow Keys

wpfnavigationlistboxitemarrow-keys

提问by Selva

My usercontrol has Listbox with Images as ListboxItems, here i'm facing an issue when i navigate listbox items (Images) using "Arrow Keys",i could'n navigate the items that is present in Next row, say for example ,List box contains rows of images*("I have used WrapPanel")*, if i navigate an images using Right arrow keyi cant able to move to next row,

我的用户控件具有带有图像的列表框作为列表框项目,这里我在使用“箭头键”导航列表框项目(图像)时遇到问题,我无法导航下一行中存在的项目,例如,列表框包含图像行* “我使用过 WrapPanel”*,如果我使用右箭头键导航图像,则无法移动到下一行,

<ListBox.ItemContainerStyle>
   <Style TargetType="{x:Type ListBoxItem}">
   <Setter Property="KeyboardNavigation.DirectionalNavigation" Value="Cycle" />
   <Setter Property="IsTabStop" Value="True" />
   </Style>
</ListBox.ItemContainerStyle>

回答by josh2112

Based on this answerwhich almost worked, but not quite.

基于这个几乎有效但不完全有效的答案

Put a KeyDownevent on your ListBox and use its ItemsCollectionto select the next or previous element when you see a Right or Left keypress.

KeyDown在 ListBox 上放置一个事件,并ItemsCollection在您看到向右或向左按键时使用它来选择下一个或上一个元素。

That moves the selection, but not the keyboard focus (dotted line), so you must also call MoveFocuson the element that has Keyboard focus.

这会移动选择,但不会移动键盘焦点(虚线),因此您还必须调用MoveFocus具有键盘焦点的元素。

private void ListBox_KeyDown( object sender, KeyEventArgs e )
{
    var list = sender as ListBox;
    switch( e.Key )
    {
        case Key.Right:
            if( !list.Items.MoveCurrentToNext() ) list.Items.MoveCurrentToLast();
            break;

        case Key.Left:
            if( !list.Items.MoveCurrentToPrevious() ) list.Items.MoveCurrentToFirst();
            break;
    }

    e.Handled = true;
    if( list.SelectedItem != null )
    {
        (Keyboard.FocusedElement as UIElement).MoveFocus( new TraversalRequest( FocusNavigationDirection.Next ) );
    }
}

Finally, make sure you have IsSynchronizedWithCurrentItem="True"on your ListBox.

最后,确保你有IsSynchronizedWithCurrentItem="True"你的 ListBox。

This will give you the wrap-around behaviour that you want.

这将为您提供所需的环绕行为。