如何以Xamarin形式检测列表视图滚动方向 [英] How to detect list view scrolling direction in xamarin forms

查看:94
本文介绍了如何以Xamarin形式检测列表视图滚动方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图检测列表视图的滚动方向.我的需求是在列表视图向上滚动和向下滚动时需要实现不同的功能.请提出任何有关检测列表视图滚动方向的想法.我在列表视图中尝试了以下语法.

I have tried to detect the scrolling direction of the list view. My requirement is need to implement different functionality while list view scrolling up and scrolling down. Please suggest any idea for detecting list view scrolling direction. I have tried below syntax in my list view.

 <StackLayout>
    <Label x:Name="Direction" />
    <ListView ItemsSource="{Binding Items}" HasUnevenRows = "true" ItemAppearing="Handle_ItemAppearing" IsPullToRefreshEnabled = "true">
    <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout>
                    <Label Text = "{Binding}" />
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
    </ListView.ItemTemplate>
        </ListView>
</StackLayout>

推荐答案

默认情况下,我认为您无法执行此操作,您只能对正在显示或消失的项目进行操作.因此,您要么需要通过创建一些代码来获取(消失的)项的索引,然后查看索引是变高还是变低,以确定某人是向上滚动还是向下滚动,然后使用该代码.或者,您需要连接一个自定义渲染器,但是我不确定本机控件是否也有任何东西可以检测到.

I don't think you can do it by default, you can only act on a item that is appearing or disappearing. So, you either need to work with that by creating some code which gets the index of (dis)appearing items and and see if the indexes are getting higher or lower to determine whether someone is scrolling up or down. Or you need to hook up a custom renderer, but I'm not sure the native controls have anything to detect this either.

我为您准备了一个非常基本的示例,您可以在此处找到完整代码.

I've whipped up a very basic example for you, you can find the full code here.

基本上可以抓住可用的事件,跟踪类变量中的最后一个索引,并将其与出现的项目的当前索引进行比较.

Basically hook into the event available, keep track of the last index in a class variable and compare it to the current index of the item that is appearing.

private void Handle_ItemAppearing (object sender, Xamarin.Forms.ItemVisibilityEventArgs e)
{
    var currentIdx = Items.IndexOf ((string)e.Item);

    if (currentIdx > _lastItemAppearedIdx)
        Direction.Text = "Up";
    else
        Direction.Text = "Down";

    _lastItemAppearedIdx = Items.IndexOf ((string)e.Item);
}

在这段代码中,我只是将其显示在Label中,但是您当然可以创建一些枚举来返回或触发事件,或者使用某些枚举来使代码更具可重用性.这是运行中的代码:

In this code I simply show it in a Label, but of course you can create some enum to return or fire an event or something to make the code some more reusable. Here is the code in action:

这篇关于如何以Xamarin形式检测列表视图滚动方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆