WPF ListBox OnScroll事件

10
我试图找出如何做某件应该很简单的事情。
我想要的是每当滚动 ListBox 控件时触发一个事件。ListBox 是动态创建的,因此我需要一种从代码后台实现它的方法(但欢迎使用 XAML 解决方案,因为它给了我一个起点)。
感谢您提供任何想法。
1个回答

15
在XAML中,您可以像这样访问ScrollViewer并添加事件:
<ListBox Name="listBox" ScrollViewer.ScrollChanged="listBox_ScrollChanged"/>

更新
这可能是您在代码后端需要的内容:

List<ScrollBar> scrollBarList = GetVisualChildCollection<ScrollBar>(listBox);
foreach (ScrollBar scrollBar in scrollBarList)
{
    if (scrollBar.Orientation == Orientation.Horizontal)
    {
        scrollBar.ValueChanged += new RoutedPropertyChangedEventHandler<double>(listBox_HorizontalScrollBar_ValueChanged);
    }
    else
    {
        scrollBar.ValueChanged += new RoutedPropertyChangedEventHandler<double>(listBox_VerticalScrollBar_ValueChanged);
    }
}

使用GetVisualChildCollection实现:

public static List<T> GetVisualChildCollection<T>(object parent) where T : Visual
{
    List<T> visualCollection = new List<T>();
    GetVisualChildCollection(parent as DependencyObject, visualCollection);
    return visualCollection;
}
private static void GetVisualChildCollection<T>(DependencyObject parent, List<T> visualCollection) where T : Visual
{
    int count = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < count; i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(parent, i);
        if (child is T)
        {
            visualCollection.Add(child as T);
        }
        else if (child != null)
        {
            GetVisualChildCollection(child, visualCollection);
        }
    }
}

非常好的答案。我还没有时间去实现它,看看它是否完全正确,但它听起来是正确的。谢谢你的帮助。 - riwalk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接