2

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

pixel
  • 9,653
  • 16
  • 82
  • 149

2 Answers2

1

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.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • Thanks Grant but in that case scrollviewer will always show even if Listbox is empty and it will show "This is the end" message which is what I do not want. I load this list dynamically with data, so no message should show if ListBox is empty, only once data is loaded and user scrolls to the bottom. Then I will load more data, that is why I need to detect when scroll bar of my ListBox is scrolled to the end. – pixel Dec 25 '15 at 04:04
  • That is it. Just using myListBox.Items.Count() instead of Any(). Thanks Grant, Merry X-mass – pixel Dec 25 '15 at 04:51
0
    private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
    {
        // Get the border of the listview (first child of a listview)
        var border = VisualTreeHelper.GetChild(sender as ListView, 0) as Decorator;

        // Get scrollviewer
        var scrollViewer = border.Child as ScrollViewer;

        if (scrollViewer.VerticalOffset == scrollViewer.ScrollableHeight)
        {
            //Write your code here.
        }
    }
Amir Touitou
  • 3,141
  • 1
  • 35
  • 31