Monday, July 28, 2008

MouseWheel support in Silverlight 2.0 without Javascript code

Yes. Its possible eventhough we are using 'onmousewheel' event of Javascript object Document.

The process is simple.Just Subscribe to the onmousewheel event of document and process according to that.

Here I am going to zoom an image with the help of mouse wheel.

Initially there is an Image in the Page.xaml with a ScaleTransform named 'scale'.
<Grid>
<Image x:Name="img" Source="Hand.jpg" Stretch="None" VerticalAlignment="Top" HorizontalAlignment="Left">
<Image.RenderTransform>
<ScaleTransform x:Name="scale" ScaleX="1" ScaleY="1" />
</Image.RenderTransform>
</Image>
</Grid>

Step1:Subscribe to the onmousewheel event

public Page() {
InitializeComponent();
HtmlPage.Document.AttachEvent("onmousewheel", new EventHandler<HtmlEventArgs>(ondown));
}

Step 2 : Handle the ScaleTransform according to the direction

void ondown(object send,HtmlEventArgs arg)
{
object c= arg.EventObject.GetProperty("wheelDelta");
if (c != null)
{
int delta = int.Parse(c.ToString());
if (delta > 0)
{
scale.ScaleX = scale.ScaleX + .1;
scale.ScaleY = scale.ScaleY + .1;
}
else if(scale.ScaleX >.1)
{
scale.ScaleX = scale.ScaleX - .1;
scale.ScaleY = scale.ScaleY - .1;
}
}
}

Happy coding... :-)


No comments: