Mouse Wheel Scroll in Silverlight 2.0

Adding scroll bars in silverlight containers is difficult in itself let alone adding mouse wheel behavior to it. You can add scroll bars using this and following code snippets will help to implement mouse wheel scroll in silverlight scrollviewer.

This is what you add in page load event –

HtmlPage.Window.DetachEvent("DOMMouseScroll", OnMouseWheelTurned);
HtmlPage.Window.DetachEvent("onmousewheel", OnMouseWheelTurned);
HtmlPage.Document.DetachEvent("onmousewheel", OnMouseWheelTurned);

Mouse Wheel Turn method

private void OnMouseWheelTurned(Object sender, HtmlEventArgs args)
        {
            ScrollViewer myScroll = scrollSender as ScrollViewer;
            if (myScroll != null)
            {
                double delta = 0;
                ScriptObject e = args.EventObject;
                if (e.GetProperty("wheelDelta") != null) // IE and Opera
                {
                    delta = ((double)e.GetProperty("wheelDelta"));
                    if (HtmlPage.Window.GetProperty("opera") != null)
                        delta = -delta;
                }
                else if (e.GetProperty("detail") != null) // Mozilla and Safari
                {  delta = -((double)e.GetProperty("detail"));  }
                double scrollHeight = myScroll.ScrollableHeight / 10;
                delta = delta / 120;
                if (delta > 0)
                {
                    myScroll.ScrollToVerticalOffset(myScroll.VerticalOffset - scrollHeight);
                }
                if (delta < 0)
                {
                    myScroll.ScrollToVerticalOffset(myScroll.VerticalOffset + scrollHeight);
                }
                if (delta != 0)
                {
                    args.PreventDefault();
                    e.SetProperty("returnValue", false);
                }
            }
        }
Advertisements

About Utkarsh Puranik

Software Engineer by Profession, Gamer by Nature, Techy by Attitude and a Good Person at Heart
This entry was posted in Technology and tagged , , , , , . Bookmark the permalink.

One Response to Mouse Wheel Scroll in Silverlight 2.0

  1. Utkarsh Puranik says:

    I found this post by Nikhil Kothari on adding scroll bars in silverlight, It uses Silverlight Fx(Framework on Silverlight)

    http://www.nikhilk.net/Silverlight-MouseWheel.aspx

    Its quite nice and easy to use.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s