Search code examples
c#wpflistboxscrollview

WPF - How to add onScroll Event to ListBox and Access the ScrollViewer


I define my ListBox like this in XAML:

<ListBox Name="myListBox" 
         HorizontalContentAlignment="Stretch" 
         ScrollViewer.HorizontalScrollBarVisibility="Hidden" 
         ScrollViewer.ScrollChanged="OnScrollChanged" <- I want to create onScrollChanged event
         Grid.Row="0">
         ...
</ListBox>

Then in my cs file, I define this event:

private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
{

    var scrollViewer = (ScrollViewer)sender; //ERROR
    if (scrollViewer.VerticalOffset == scrollViewer.ScrollableHeight)
        MessageBox.Show("This is the end");
}

I am trying to detect when user scrolls to the very bottom of ListBox. But I get error that ListBox cannot be casted to Scrollviewer. How do I get the scrollviewer?

Thanks


Solution

  • Add a ScrollViewer around your ListBox in the XAML, and subscribe to the event from there.

    <ScrollViewer ScrollChanged="OnScrollChanged">
        <ListBox Name="myListBox" 
                 HorizontalContentAlignment="Stretch"
                 ScrollViewer.HorizontalScrollBarVisibility="Hidden"
                 Grid.Row="0" />
    </ScrollViewer>
    

    The code-behind can remain the same.

    In your current code, you're trying to convert your ListBox (the "sender") to a ScrollViewer, which it cannot do, so it throws an exception.