How to scroll through a listbox with down and up arrow keys in WPF?
I am using an AutoCompleteBox UserControl that uses a listbox inside of a Popup. Everything works fine, the user can type in, view suggested results, and click the result which retrieves information.
i have been trying to add arrow key event handlers so they can scroll down through the listbox that pops up with up and down arrows, and hit enter to select a result.
I have a PreviewKeyDown event on the TextBox the user types in, and inside of that:
If e.Key = Key.Up Then
txtNamesListBox.Focus()
End If
If e.Key = Key.Down Then
txtNamesListBox.Focus()
End If
The event fires and i can rea开发者_开发技巧ch these functions by setting a break point, however it doesnt set the focus to the ListBox that pops up, and i cant scroll through the results at all. is this even possible and am i way off in my attempt? I am at a loss, thanks!
You need to get a reference of the ScrollViewer
residing inside ListBox
template and use it to scroll content.
Something like following should do. (NOTE: I have not tested this code.)
Example:
ScrollViewer scrollViewer = (ScrollViewer)txtNamesListBox.Template.FindControl("ScrollViewer");
// call methods on scrollViewer
Edit:
Worked out simpler soultion. Idea is wrapping the ListBox
with a ScrollViewer
and disabling ListBox
's scrolling.
Example:
XAML:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525"
Loaded="Window_Loaded">
<Grid>
<StackPanel>
<RepeatButton Click="ScrollUp">Scroll Up</RepeatButton>
<ScrollViewer Name="scrollViewer"
ScrollViewer.VerticalScrollBarVisibility="Hidden"
MaxHeight="200">
<ListBox Name="txtNamesListBox"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled"></ListBox>
</ScrollViewer>
<RepeatButton Click="ScrollDown">Scroll Down</RepeatButton>
</StackPanel>
</Grid>
</Window>
Code Behind:
Class MainWindow
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
txtNamesListBox.ItemsSource = Enumerable.Range(1, 50).Select(Function(i As Int32) i.ToString())
End Sub
Private Sub ScrollDown(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + 10)
End Sub
Private Sub ScrollUp(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - 10)
End Sub
End Class
精彩评论