You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Forms中如何判断用户是否滚动到ListView顶部或底部

判断ListView是否滚动到顶部/底部的实现方法

你可以通过监听ListView的Scrolled事件,结合滚动偏移量和视图尺寸来判断当前是否处于顶部或底部位置,具体实现如下:

1. 更新XAML代码,添加滚动事件

给你的ListView添加Scrolled事件绑定:

<ListView
    ItemTapped="MyListView_ItemTapped"
    Grid.Row="0" Grid.Column="0"
    IsRefreshing="{Binding IsRefreshing}" 
    RefreshCommand="{Binding UpdateList}"
    ItemTemplate="{StaticResource chatDataTemplateSelector}"  
    ItemsSource="{Binding MessageList}"
    Background="#1D2733" 
    IsPullToRefreshEnabled="True" 
    RefreshControlColor="Cyan"  
    Margin="0,0,0,0" 
    SeparatorColor="Transparent"  
    x:Name="MyListView" 
    HasUnevenRows="true"
    Scrolled="MyListView_Scrolled"
>
</ListView>

2. 在后台代码实现滚动判断逻辑

在对应的.xaml.cs文件中编写Scrolled事件的处理方法:

private void MyListView_Scrolled(object sender, ScrolledEventArgs e)
{
    var listView = sender as ListView;
    if (listView == null) return;

    // 判断是否处于列表顶部
    bool isAtTop = e.ScrollY == 0;

    // 判断是否滚动到列表底部
    // 滚动偏移量 + 列表可视高度 >= 可滚动内容总高度,即为底部
    bool isAtBottom = e.ScrollY + listView.Height >= listView.ScrollableHeight;

    // 根据判断结果执行对应业务逻辑
    if (isAtTop)
    {
        // 已到达顶部,执行你的逻辑(比如提示无更多历史消息)
    }
    if (isAtBottom)
    {
        // 已到达底部,执行你的逻辑(比如自动加载新消息、提示已到最新消息)
    }
}

注意事项

  • 当列表内容总高度小于等于列表可视高度时,isAtTop和isAtBottom会同时为true,可根据业务需求添加额外判断(比如listView.ScrollableHeight <= listView.Height)来区分这种场景。
  • 因为你的ListView设置了HasUnevenRows="true",ScrollableHeight会自动计算所有行的实际总高度,无需额外处理行高问题。

效果展示:
MyChat

内容的提问来源于stack exchange,提问作者Katya Appazova

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 12:45:44