用于在用户交互时停止的AutoScrolling的ListView行为

时间:2015-12-06 23:27:01

标签: c# listview win-universal-app uwp-xaml

我尝试在UAP中使用新的行为特征。我使用此行为:

public sealed class AutoScrollToLastItemBehavior : Behavior<ListView>
{
    private bool _collectionChangedSubscribed;

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.SelectionChanged += SelectionChanged;
        AssociatedObject.DataContextChanged += DataContextChanged;
    }

    private void SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ScrollToBottom();
    }

    private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        ScrollToBottom();
    }

    private void DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
    {
        var collection = AssociatedObject.ItemsSource as INotifyCollectionChanged;
        if (collection == null || _collectionChangedSubscribed) return;

        collection.CollectionChanged += CollectionChanged;
        _collectionChangedSubscribed = true;
    }

    private void ScrollToBottom()
    {
        var selectedIndex = AssociatedObject.Items?.Count - 1;

        if (!selectedIndex.HasValue || selectedIndex < 0)
            return;

        AssociatedObject.SelectedIndex = selectedIndex.Value;
        AssociatedObject.UpdateLayout();
        AssociatedObject.ScrollIntoView(AssociatedObject.SelectedItem);
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.SelectionChanged -= SelectionChanged;
        AssociatedObject.DataContextChanged -= DataContextChanged;

        var collection = AssociatedObject.ItemsSource as  INotifyCollectionChanged;
        if (collection == null || !_collectionChangedSubscribed) return;
        collection.CollectionChanged -= CollectionChanged;
        _collectionChangedSubscribed = false;
    }
}

此代码效果很好。但我希望当用户与ListView交互时,AutoScrolling停止运行。我找到了一些样本,但大多数基于WPF,并且UWP中没有一些函数或属性。

所以实际上我没有找到一种实现AutoScroll的方法,如果User自己滚动它就会停止工作。有人可能是这个想法吗?

问候

1 个答案:

答案 0 :(得分:0)

这实际上取决于用户与ListView&#34;进行交互的意思。如果您指的是有人手动滚动 - 您可以查看ViewChanged事件或VerticalOffset的{​​{1}},看看它是否在收集更改之前滚动到底部。其他互动可能是您的应用自定义的内容,因此您必须自己检测它们。在查看这些详细信息之前,您需要先从ScrollViewer模板访问ScrollViewer