Zoom-in and out in Silverlight

I’ve been asked this ample times at my work place – how to implement a zoom in/out effect on any Silverlight Control.

So let us take an example:-

You have your contents inside a grid, typically named LayoutRoot, and you want to zoom it when Mouse is placed on it and get back to original shape when Mouse is removed from it.

This effect can be achieved by ScaleTransform which is a child of RenderTransform.  This also means, elements who have RenderTransform as a child node can only implement this feature. So if you have any control which does not have RenderTransform as a child node – just encapsulate it in a Grid.

Your XAML code appears as:-

<Grid x:Name=”LayoutRoot” Width=”311″   MouseEnter=”LayoutRoot_MouseEnter” MouseLeave=”LayoutRoot_MouseLeave”>
<Grid.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX=”1″/>
</TransformGroup>
</Grid.RenderTransform>
</Grid>

<Grid x:Name="LayoutRoot" Width="311"   MouseEnter="LayoutRoot_MouseEnter" MouseLeave="LayoutRoot_MouseLeave">

<Grid.RenderTransform>

<TransformGroup>

<ScaleTransform ScaleX="1"/>

</TransformGroup>

</Grid.RenderTransform>

</Grid>

Insert a story board in the UserControl:-


<UserControl.Resources>

<Storyboard x:Name="grow">

<DoubleAnimation

Storyboard.TargetName="LayoutRoot"

Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"

From="1" To="1.5" SpeedRatio="3">

</DoubleAnimation>

<DoubleAnimation

Storyboard.TargetName="LayoutRoot"

Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"

From="1" To="1.5" SpeedRatio="3">

</DoubleAnimation>

</Storyboard>

</UserControl.Resources>

The first animation is for ScaleX and the second animation is for ScaleY. You can change the sections in BLUE as per your need.

The code file appears as:


private void LayoutRoot_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)

{

this.grow.Begin();

}

private void LayoutRoot_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)

{

this.grow.Stop();

}

That’s as simple as that :) Happy Zooming!

Related Posts: