Tono Nam
Tono Nam

Reputation: 36048

Place storyboard in style or datatemplate

I have a storyboard that animates an image's width. I created the animation with expression blend:

<Storyboard x:Key="Storyboard1">
    <DoubleAnimationUsingKeyFrames 
             Storyboard.TargetProperty="(FrameworkElement.Width)" 
             Storyboard.TargetName="imageFoo">
            <EasingDoubleKeyFrame KeyTime="0:0:0.9" Value="335">
                <EasingDoubleKeyFrame.EasingFunction>
                    <BackEase EasingMode="EaseOut"/>
                </EasingDoubleKeyFrame.EasingFunction>
            </EasingDoubleKeyFrame>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>

The problem is that I want to assign that storyboard to all the images in my application not just for the image imageFoo. I will like to start that animation when the MouseEnters an image. How can I do that?

Upvotes: 0

Views: 708

Answers (1)

Andy
Andy

Reputation: 6466

You need to remove the Target name from the storyboard and also move the trigger into a style, there is no code behind required to do this thankfully

In your App.xaml file (or in any resources collection).

 <Application.Resources>
        <Style TargetType="{x:Type Image}">
            <Style.Triggers>
                <EventTrigger RoutedEvent="MouseEnter">
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Width)">
                                <EasingDoubleKeyFrame KeyTime="0:0:0.9" Value="335">
                                    <EasingDoubleKeyFrame.EasingFunction>
                                        <BackEase EasingMode="EaseOut"/>
                                    </EasingDoubleKeyFrame.EasingFunction>
                                </EasingDoubleKeyFrame>
                            </DoubleAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Style.Triggers>
        </Style>
    </Application.Resources>

By declaring a style with no x:Key and simply giving a TargetType you're basically telling WPF that it's supposed to apply to every single element in the visual tree with that type.

Upvotes: 2

Related Questions