10

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.

1 Answer 1

15

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice answer. I haven't had the time to implement it to see if it does everything correctly, but it sure sounds right. Thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.