sbaeumlisberger / VirtualizingWrapPanel

Implementation of a comprehensive VirtualisingWrapPanel for WPF
MIT License
242 stars 33 forks source link

Wrapping keyboard navigation #37

Closed milos12345 closed 2 years ago

milos12345 commented 2 years ago

In explorer's grid view when the last item is selected in a row, pressing right-arrow will move focus to the first item in the next row. I have tried all options of KeyboardNavigation.DirectionalNavigation but none of those work with VirtualizingWrapPanel. Is that possible?

Version Info Package Version: 1.5.4 but same is in sample app for 1.5.7 .NET Version: 4.8 Windows 10 21H1

sbaeumlisberger commented 2 years ago

You could use a custom key event handler. For example like that:

<ListView
   ...
   PreviewKeyDown="ListView_PreviewKeyDown"
   ...
private void ListView_PreviewKeyDown(object sender, KeyEventArgs e)
{
    var listView = (ListView)sender;

    var currentItem = listView.ItemContainerGenerator.ItemFromContainer((DependencyObject)Keyboard.FocusedElement);

    int targetIndex;
    switch (e.Key)
    {
        case Key.Left:
            targetIndex = listView.Items.IndexOf(currentItem) - 1;
            break;
        case Key.Right:
            targetIndex = listView.Items.IndexOf(currentItem) + 1;
            break;
        default:
            return;
    }
    if (targetIndex >= 0 && targetIndex < listView.Items.Count)
    {
        ((UIElement)listView.ItemContainerGenerator.ContainerFromIndex(targetIndex)).Focus();
    }
    e.Handled = true;
}

I think that's something I will also add to the GridView control.

milos12345 commented 2 years ago

That works, thank you! If you add it to the library, it might be good to be an optional property instead of default.