Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate a WPF Window left and right with a shake effect?

Could someone please show me how to animate a window from its current position. I am looking for a shake effect which simply shakes the window left and right say 5 to 6 times.

I understand that I need to use Animation.By. This is something I have started but am not getting far.

This However does not work.

<Storyboard x:Key="sbShake1" FillBehavior="Stop">
    <DoubleAnimation Storyboard.TargetName="W1" Storyboard.TargetProperty ="(Window.Left)"
                     By="10" Duration="0:0:1">
    </DoubleAnimation >
</Storyboard >

I have managed to get the right shake effect but I cannot do it from the windows current position.

<Storyboard x:Key="sbShake" RepeatBehavior ="00:00:01" SpeedRatio ="25" >
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty ="Left">
        <SplineDoubleKeyFrame KeyTime ="00:00:00.1000000" Value ="-10"/>
        <SplineDoubleKeyFrame KeyTime ="00:00:00.3000000" Value ="0"/>
        <SplineDoubleKeyFrame KeyTime ="00:00:00.5000000" Value ="10"/>
        <SplineDoubleKeyFrame KeyTime ="00:00:00.7000000" Value ="0"/>
    </DoubleAnimationUsingKeyFrames >
</Storyboard >

All help would be appreciated.

like image 251
darbid Avatar asked Oct 12 '25 19:10

darbid


2 Answers

Set the Left property of your window to 500 and add this code:

<Window.Triggers>
    <EventTrigger RoutedEvent="Window.MouseDown" >
        <EventTrigger.Actions>
            <BeginStoryboard>
                <Storyboard TargetProperty="Left">
                    <DoubleAnimation From="500" To="515" Duration="0:0:0.05"
                                     AutoReverse="True" RepeatBehavior="3x"
                                     FillBehavior="Stop"/>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger.Actions>
    </EventTrigger>
</Window.Triggers>

You should set the property Left of Window manually when you don't mention From="x" otherwise it set to Auto and when you try to shake your window the value of Left is NaN and an exception will be thrown.

like image 155
Ali M Avatar answered Oct 14 '25 10:10

Ali M


You could use a BounceEase to make the window shake:

<Storyboard x:Name="myStoryboard">
    <DoubleAnimation By="10" Duration="00:00:3"
                     AutoReverse="True" RepeatBehavior="1"
                     Storyboard.TargetName="W1" 
                     Storyboard.TargetProperty="Left">
        <DoubleAnimation.EasingFunction>
            <BounceEase Bounces="2" EasingMode="EaseOut" 
                        Bounciness="2" />
        </DoubleAnimation.EasingFunction>
    </DoubleAnimation>
</Storyboard>
like image 43
Emond Avatar answered Oct 14 '25 11:10

Emond