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.

We deliver solutions that accelerate the value of Azure.

Ready to experience the full power of Microsoft Azure?

Start Today

Blog Home

Stay Connected

Upcoming Events

All Events