我正在使用AutoCompleteBox UserControl,它使用Popup中的列表框。一切正常,用户可以输入,查看建议的结果,然后单击检索信息的结果。
我一直在尝试添加箭头键事件处理程序,以便他们可以向下滚动通过向上和向下箭头弹出的列表框,然后按Enter键以选择结果。
我在用户输入的TextBox上有一个PreviewKeyDown事件,其中包含:
If e.Key = Key.Up Then
txtNamesListBox.Focus()
End If
If e.Key = Key.Down Then
txtNamesListBox.Focus()
End If
事件触发并且我可以通过设置断点来实现这些功能,但是它没有将焦点设置为弹出的ListBox,并且我根本无法滚动结果。这是否可能,我在尝试中离开了?我很茫然,谢谢!
答案 0 :(得分:2)
您需要获取驻留在ScrollViewer
模板中的ListBox
的引用,并使用它来滚动内容。
以下应该做的事情。 (注意:我没有测试过这段代码。)
ScrollViewer scrollViewer = (ScrollViewer)txtNamesListBox.Template.FindControl("ScrollViewer");
// call methods on scrollViewer
制定了更简单的灵魂。 Idea用ListBox
包裹ScrollViewer
并禁用ListBox
滚动。
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>
代码背后:
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