WPF ListBox OnScroll事件

标签 wpf events listbox scroll

我试图弄清楚如何做(应该)很简单的事情。

我想要的是让ListBox控件滚动时触发事件。 ListBox是动态创建的,因此我需要一种从背后的代码中进行操作的方法(不过,XAML解决方案也受到赞赏,因为它为我提供了一些起点)。

预先感谢您的任何想法。

最佳答案

在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);
        }
    }
}

关于WPF ListBox OnScroll事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4139341/

相关文章:

c# - 如何阻止方法递归调用自己?

c# - 从Button更新文本框,单击C#

events - jQuery 更改事件未从键盘触发?

c# - Windows Phone 的 silverlight 中的文本换行问题

android - 处理 EditText 焦点的事件

c++ - 如何在 MFC 中设置菜单项旁边的复选标记?

c# - 在 WPF 中实现 CheckBoxes 的 ListBox

C# 使用 newtonsoft 删除 json 子节点

c# - 如何使用 EF 查看和编辑 DataGrid 中多个表的数据?

c# - 如何在 MVVM WPF 应用程序中控制列表框的滚动位置