How to detect ListView is scrolling up or down

て烟熏妆下的殇ゞ 提交于 2019-11-28 10:20:34
yasen

Once the ListView is Loaded you can get the ScrollViewer like this:

var sv = (ScrollViewer)VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.ListV, 0), 0);

Edit

As Romasz suggested, once you get the ScrollViewer, you can use its ViewChanged event, to monitor when it is scrolling and when it stops.

Also, here's the generic extension method that I use for traversing the visual tree:

// The method traverses the visual tree lazily, layer by layer
// and returns the objects of the desired type
public static IEnumerable<T> GetChildrenOfType<T>(this DependencyObject start) where T : class 
{
    var queue = new Queue<DependencyObject>();
    queue.Enqueue(start);

    while (queue.Count > 0) {
        var item = queue.Dequeue();

        var realItem = item as T;
        if (realItem != null) {
             yield return realItem;
        }

        int count = VisualTreeHelper.GetChildrenCount(item);
        for (int i = 0; i < count; i++) {
            queue.Enqueue(VisualTreeHelper.GetChild(item, i));
        }
    }
}

To get the ScrollViewer using this methos, do this:

var sv = yourListView.GetChildrenOfType<ScrollViewer>().First();

You can find the ScrollViewer of your ListView by using VisualTreeHelper. For example like this:

// method to pull out a ScrollViewer
public static ScrollViewer GetScrollViewer(DependencyObject depObj)
{
    if (depObj is ScrollViewer) return depObj as ScrollViewer;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        var child = VisualTreeHelper.GetChild(depObj, i);

        var result = GetScrollViewer(child);
        if (result != null) return result;
    }
    return null;
}

Once you have a ScrollViewer you can subscribe to its events:

GetScrollViewer(yourListView).ViewChanged += yourEvent_ViewChanged;
Đăng Hoàng Nguyễn

You must load data to listview before getting scrollview. If listview has empty row then scrollview you get will be null.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!