Tuesday, May 18, 2010

Making the ScrollViewer Talk in Silverlight 4

Recently I came across the requirement to react to the fact that a user had scrolled a view to the bottom. It sounded easy at first because I imagined hooking into a scroll viewer changed event, listening to the event args, and then reacting when it was done. The only problem was that I couldn't find the appropriate event to bind to!

A quick search found that many people are having the same problem. The "important" events are hidden inside the ScrollViewer, down at the bars. A few solutions walk the visual tree down to the bars and hook in, but I wanted something that was a little more generic and clean.

Fortunately, we can get what we want by listening to properties. I'm going to give an example for the "VerticalOffset" property which shows how much the vertical scroll is offset from the height. When this equals the height, it has been scrolled to the bottom. This example, however, isn't just for scroll bars - it will work with any type of dependency property you want to listen to.

The trick is to create a binding for the property you want to listen to. Then, bind to the binding using a dependency property, and listen for that to change!

In our case, we want to watch the vertical offset for a ScrollViewer. Here is the binding:

var binding = new Binding("VerticalOffset") { Source = myScrollViewer }; 

Next, I want to listen to that binding and react when it changes. I can, for example, interrogate the scroll viewer and see if it's reached the bottom (note that if I wanted, I could also fire a command and indirectly bind the property change to an ICommand on a view model).

var offsetChangeListener = DependencyProperty.RegisterAttached(
   new PropertyMetadata(_OnScrollChanged)); 
myScrollViewer.SetBinding(offsetChangeListener, binding);
public void _OnScrollChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) 
   // do something with the scroll viewer 

That's it! You can wrap this into a behavior that you simply drop onto the ScrollViewer and you can make even the most stubborn ones sing.

Jeremy Likness


  1. This is really a wonderful solution to the problem! Many thanks for this!

  2. Is there any difference between using attached and dependency property in this case?

  3. This seems to cause memory leaks according to WinDbg.