xamarin 如何检测CollectionView是以编程方式滚动还是由用户滚动?

rsl1atfo  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(117)

我有一个CollectionView,我需要确定它是否已经以编程方式滚动,或者用户是否已经滚动了CollectionView。
这两个事件都会触发Scrolled事件。

siv3szwd

siv3szwd1#

首先,如果CollectionView正在以编程方式滚动,您应该知道,因为是您在做这件事。
从您的问题中,我推断您试图在与所讨论的CollectionView没有直接联系的地方进行区分,可能是因为您试图将关注点分开。
你可以做的一件事是子类化CollectionView, Package 对CollectionView.ScrollTo()方法的调用,并调用一个单独的事件处理程序:

public ProgScrollEventArgs : EventArgs
{
    public int Index { get; init; }

    public ProgScrollEventArgs(int index)
    {
        Index = index;
    }
}

public MyCollectionView : CollectionView
{
    public event EventHandler<ProgScrollEventArgs> ProgrammaticallyScrolled;

    // New method to call
    public void ScrollToIndex(int index)
    {
        // Relay call to base method
        ScrollTo(index);

        // Invoke separate event handler
        ProgrammaticallyScrolled?.Invoke(this, new ProgScrollEventArgs(index));
    }
}

然后,在XAML中的所有地方使用MyCollectionView类而不是CollectionView,并订阅ProgrammaticallyScrolled事件:

<MyCollectionView
    x:Name="MyCollectionView"
    ItemsSource="{Binding SomeItems}"
    ProgrammaticallyScrolled="OnProgScroll" />

在代码隐藏中,您将添加事件处理程序:

private void OnProgScroll(object sender, ProgScrollEventArgs e)
{
    // handle event here
}

您需要使用新的ScrollToIndex()方法来进行编程滚动:

MyCollectionView.ScrollToIndex(5);

或者,您也可以订阅代码隐藏中的事件:

MyCollectionView.ProgrammaticallyScrolled += OnProgScroll;

相关问题