WPF-如何将onScroll事件添加到ListBox并访问ScrollViewer
本文关键字:ListBox 访问 ScrollViewer 添加 事件 onScroll WPF- | 更新日期: 2023-09-27 18:28:11
我在XAML中这样定义我的ListBox:
<ListBox Name="myListBox"
HorizontalContentAlignment="Stretch"
ScrollViewer.HorizontalScrollBarVisibility="Hidden"
ScrollViewer.ScrollChanged="OnScrollChanged" <- I want to create onScrollChanged event
Grid.Row="0">
...
</ListBox>
然后在我的cs文件中,我定义了这个事件:
private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
{
var scrollViewer = (ScrollViewer)sender; //ERROR
if (scrollViewer.VerticalOffset == scrollViewer.ScrollableHeight)
MessageBox.Show("This is the end");
}
我正在尝试检测用户何时滚动到ListBox的最底部。但我得到了一个错误,列表框不能广播到滚动查看器。如何获取滚动查看器?
感谢
在XAML中的ListBox
周围添加一个ScrollViewer
,然后从那里订阅事件。
<ScrollViewer ScrollChanged="OnScrollChanged">
<ListBox Name="myListBox"
HorizontalContentAlignment="Stretch"
ScrollViewer.HorizontalScrollBarVisibility="Hidden"
Grid.Row="0" />
</ScrollViewer>
后面的代码可以保持不变。
在当前代码中,您正试图将ListBox
("发送方")转换为ScrollViewer
,但它无法做到这一点,因此它抛出了一个异常。
private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
{
// Get the border of the listview (first child of a listview)
var border = VisualTreeHelper.GetChild(sender as ListView, 0) as Decorator;
// Get scrollviewer
var scrollViewer = border.Child as ScrollViewer;
if (scrollViewer.VerticalOffset == scrollViewer.ScrollableHeight)
{
//Write your code here.
}
}