Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF ListBox OnScroll Event

I am trying to figure out how to do something that (should) be fairly simple.

What I want is to get an event to fire anytime a ListBox control is scrolled. The ListBox is dynamically created, so I need a way to do it from the code behind (however XAML solutions are appreciated as well, as it gives me something to start from).

Thanks in advance for any ideas.

like image 853
riwalk Avatar asked Nov 09 '10 22:11

riwalk


1 Answers

In XAML you can access the ScrollViewer and add events like this:

<ListBox Name="listBox" ScrollViewer.ScrollChanged="listBox_ScrollChanged"/>

Update
This is probably what you need in code behind:

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

With an implementation of 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);
        }
    }
}
like image 70
Fredrik Hedblad Avatar answered Sep 21 '22 19:09

Fredrik Hedblad