Search code examples
wpfxamlkeyboard

Disable keyboard arrow navigation in a ListView


I have a ListView and I am trying to disable the keyboard navigation between individual items. I tried to set KeyboardNavigation.DirectionalNavigation="None" to the ListView, to its PanelTemplate and also to individual items. None of it worked.

Also, the keyboard directional navigation is messed up - the panel is a wrappanel and pressing the arrows navigates chaotic, sometimes it also cycles just between two children with no chance of jumping to other ones with the arrows. That is why I want to disable, though correcting it would be even better.

Here is the relevant code:

<ListView.ItemsPanel>
    <ItemsPanelTemplate>
        <WrapPanel Orientation="Horizontal" 
                   Width="210" 
                   Margin="0,12" 
                   KeyboardNavigation.DirectionalNavigation="None" />
    </ItemsPanelTemplate>
</ListView.ItemsPanel>

<ListView.ItemTemplate>
    <DataTemplate>
        <Border Width="24" 
                Height="24" 
                Background="White"
                BorderBrush="Black" 
                BorderThickness="1 1 1 1" 
                Margin="0"
                KeyboardNavigation.IsTabStop="False" 
                KeyboardNavigation.DirectionalNavigation="None">
            <TextBlock Text="{Binding Text}" 
                       FontSize="20" 
                       VerticalAlignment="Center" 
                       HorizontalAlignment="Center" 
                       x:Name="textBlock" 
                       FontFamily="Verdana, Arial"/>
        </Border>
    </DataTemplate>
</ListView.ItemTemplate>

Solution

  • just add a handler for the PreviewKeyDown event:

    private void listView1_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        switch(e.Key)
        {
            case Key.Left:
            case Key.Right:
            case Key.Up:
            case Key.Down:
                e.Handled = true;
                break;
            default:
                break;
        }
    }