I'm creating a WPF application which the List View will load some order from database. Due to some situation, only a NumPad keyboard can be used when this application is in used in actual situation. However, I've been searching over the internet but do not get this to work.
What I want to do is use the NumPad8 and NumPad2 to navigate the list item up and down. Just like the arrow key on the normal keyboard. And let the focus set on the first item whenever the list is load.
I'm using MVVM style but it is fine if the code need to put behind the code.
Here is my XAML Code:
<ListView Name="PreparingView" ItemContainerStyle="{StaticResource CenterAlignmentStyle}" Background="Lavender" FontSize="25" Width="450" FontWeight="Bold" ItemsSource="{Binding PreparingList}"
HorizontalAlignment="Left" HorizontalContentAlignment="Left" Foreground="Blue" SelectedValue="{Binding CurrentSelection, Mode=TwoWay}" Margin="10,80,0,180">
<ListView.View>
<GridView ColumnHeaderContainerStyle="{StaticResource noHeaderStyle}">
<GridViewColumn Width="Auto" DisplayMemberBinding="{Binding QNum}"/>
</GridView>
</ListView.View>
</ListView>
Really appreciates if anyone can help. Thank you.
This should do what you want:
Example XAML:
<Window x:Class="WpfApp14.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp14"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
<Grid>
<ListView Name="lvTest" KeyDown="lvTest_KeyDown">
<ListView.Items>
<ListViewItem>item 1</ListViewItem>
<ListViewItem>item 2</ListViewItem>
<ListViewItem>item 3</ListViewItem>
<ListViewItem>item 4</ListViewItem>
<ListViewItem>item 5</ListViewItem>
<ListViewItem>item 6</ListViewItem>
<ListViewItem>item7</ListViewItem>
<ListViewItem>item 8</ListViewItem>
</ListView.Items>
</ListView>
</Grid>
</Window>
Code Behind:
private void lvTest_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.NumPad2)
{
if (lvTest.SelectedIndex < lvTest.Items.Count -1)
{
lvTest.SelectedIndex++;
}
else
{
lvTest.SelectedIndex = 0;
}
}
else if (e.Key == Key.NumPad8)
{
if (lvTest.SelectedIndex > 0)
{
lvTest.SelectedIndex--;
}
else
{
lvTest.SelectedIndex = lvTest.Items.Count - 1;
}
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
lvTest.Focus();
lvTest.SelectedIndex = 0;
}