Search code examples
silverlight

How to use one animation for several controls in Silverlight


I'm just studying Silverlight (in C#) and I got a problem. I have 14 rectangles and their width/Height are set to "Auto". I want to create animation on MouseEnter/MouseLeave. Animation will be just changing the width/Height.

I did it using Expression Blend for Silverlight 5, and everything is OK but it made HUGE code. Can I make some resource animation for all rectangles ?

This is the XAML code made by Blend, and I have 14 such blocks:

<Storyboard x:Name="BigTableOne_MouseEnter">
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleX)" Storyboard.TargetName="Table1">
            <EasingDoubleKeyFrame KeyTime="0" Value="1"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="1.04"/>
        </DoubleAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleY)" Storyboard.TargetName="Table1">
            <EasingDoubleKeyFrame KeyTime="0" Value="1"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="1.04"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>
    <Storyboard x:Name="BigTableOne_MouseLeave">
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleX)" Storyboard.TargetName="Table1">
            <EasingDoubleKeyFrame KeyTime="0" Value="1.04"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="1"/>
        </DoubleAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleY)" Storyboard.TargetName="Table1">
            <EasingDoubleKeyFrame KeyTime="0" Value="1.04"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="1"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>

Solution

  • All your storyboards have same content besides "Storyboard.TargetName" property.So you can just delete this property and set it at runtime dynamically.

    You can find more detail here.