Updated Silverlight Mouse Wheel Behavior

A while ago I showed how you could hook into the DOM's MouseWheel events and create a Behavior to attach Mouse Wheel scrolling to any ScrollViewer. You can read about it from the sidebar on the right.

Since then Silverlight 3 has been released and along with it we have Mouse Wheel support backed in, we can now build a much simpler Behavior to add Mouse Wheel functionality toScrollViewer. Here it is.

public class MouseWheelScrollBehavior : Behavior<ScrollViewer>

{

    protected override void OnAttached()

    {

        base.OnAttached();

 

        AssociatedObject.MouseWheel += OnMouseWheel;

    }

 

    protected override void OnDetaching()

    {

        base.OnDetaching();

 

        AssociatedObject.MouseWheel -= OnMouseWheel;

    }

 

    private void OnMouseWheel(object sender, MouseWheelEventArgs e)

    {

        var offset = AssociatedObject.VerticalOffset;

 

        AssociatedObject.ScrollToVerticalOffset(offset + (e.Delta * -0.5));

    }

}

 

 

kick it on DotNetKicks.com

Shout It Kick It submit to reddit

3 Comments

  1. Kirupa (MS)
    Kirupa (MS)
    Tuesday, August 25, 2009
    Hi Nigel - the SL mouse wheel only works on Windows. If you are running on a Mac, the SL mouse wheel implementation will not work. What you do gain is the ability to use the mouse wheel in full screen and (I think) out of browser mode. A good tradeoff would be one where you use the DOM-based mouse wheel approach at all times and switch to the SL3 based version during offline and out of browser (again, not sure) modes =) Cheers! Kirupa
  2. Kirupa (MS)
    Kirupa (MS)
    Tuesday, August 25, 2009
    I should clarify - I meant, full screen instead of "offline" in the last sentence. :-)
  3. Nigel Sampson
    Nigel Sampson
    Tuesday, August 25, 2009
    Thanks for the heads up. I'll revise it later.

Comments are closed