Selva
Selva

Reputation: 1360

Navigate listboxitems using arrow Keys

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 key i cant able to move to next row,

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

Upvotes: 1

Views: 11157

Answers (1)

josh2112
josh2112

Reputation: 848

Based on this answer which almost worked, but not quite.

Put a KeyDown event on your ListBox and use its ItemsCollection to select the next or previous element when you see a Right or Left keypress.

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

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.

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

Upvotes: 2

Related Questions