Jeff Prosise's Blog

Mousewheel Zooms in Silverlight 2.0

A few weeks ago I posted a short code sample demonstrating how to do mousewheel zooms in Silverlight 1.1. They're easier to do in Silverlight 2.0 and can be done without calling out of managed code, thanks to the new HtmlWindow class (and the HtmlPage.Window property, which returns a reference to an HtmlWindow).

Here's a summary. First, assume you have a ScaleTransform that facilitates zooms:

<ScaleTransform x:Name="ZoomTransform" />

Next, when the page loads, use HtmlWindow.AttachEvent to register a managed handler for mousewheel events:

HtmlPage.Window.AttachEvent("DOMMouseScroll", OnMouseWheelTurned);

HtmlPage.Window.AttachEvent("onmousewheel", OnMouseWheelTurned);

HtmlPage.Document.AttachEvent("onmousewheel", OnMouseWheelTurned);

Here's the event handler that responds to mousewheel events by manipulating the ScaleTransform:

private void OnMouseWheelTurned(Object sender, HtmlEventArgs args)

{

    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"));

    }

 

    if (delta > 0)

    {

        // Zoom in

        ZoomTransform.ScaleX += 0.1;

        ZoomTransform.ScaleY += 0.1;

    }

    else if (delta < 0)

    {

        // Zoom out

        ZoomTransform.ScaleX -= 0.1;

        ZoomTransform.ScaleY -= 0.1;

    }

 

    if (delta != 0)

    {

        args.PreventDefault();

        e.SetProperty("returnValue", false);

    }

}

Anything affected by the ScaleTransform will now scale up and down with mousewheel movements.

My mousewheel event handler is browser-independent and correctly reports the direction of travel, but it doesn't take into account the differences in the magnitude of travel reported by various browsers. Scott Hanselman pointed me to an excellent blog post by Pete Blois that includes downloadable source code for a MouseWheelHelper class that accounts for differences in magnitude, too. Check it out if you want to make mousewheel handling simple as pie in Silverlight 2.0.

On Mar 18 2008 4:11 PMBy jprosise With 9 Comments

Comments (9)

  1. Its always useful if you upload a small source code file. That will help a newbie like me

  2. When i try to add your code in page.xaml.cs ..i get this error

    Expected class, delegate, enum, interface, or struct

  3. Hurray! I've been struggling to figure this out for a while now.
    Thank you!

    p.s.
    I also needed to include:
    using System.Windows.Browser;

Leave a Comment