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

本秂侑毒 提交于 2020-01-14 14:57:04

问题


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.


回答1:


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.




回答2:


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>


来源:https://stackoverflow.com/questions/17434877/animate-a-wpf-window-left-and-right-with-a-shake-effect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!