How to animate a Window?

2019-03-29 13:05发布

问题:

With WPF, how do I animate the position of a Window. I tried to simply animate the Left/Top properties, but it didn't work. Does anybody know how?

Thanks!

回答1:

Just create a Storyboard for the window you're trying to animate.

Here's an example for a window named w1:

<Window.Triggers>
  <EventTrigger RoutedEvent="Window.Loaded">
    <EventTrigger.Actions>
      <BeginStoryboard>
        <Storyboard BeginTime="0" Duration="Forever">
          <DoubleAnimation Storyboard.TargetName="w1" Storyboard.TargetProperty="(Window.Top)" From="0" To="300" AutoReverse="true" BeginTime="0:0:0" Duration="0:0:1" RepeatBehavior="Forever"/>
          <DoubleAnimation Storyboard.TargetName="w1" Storyboard.TargetProperty="(Window.Left)" From="0" To="400" AutoReverse="true" BeginTime="0:0:0" Duration="0:0:2" RepeatBehavior="Forever"/>
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger.Actions>
  </EventTrigger>  
</Window.Triggers>


回答2:

This will do fade effect while window is showing up:

<Window.Triggers>
    <EventTrigger RoutedEvent="Loaded">
        <BeginStoryboard>
            <Storyboard Duration="00:00:3" Storyboard.TargetProperty="Opacity">
                <DoubleAnimation From="0" To="1"/>
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
</Window.Triggers>


回答3:

Maybe you can try adding a StoryBoard to it using Expression Blend. You can control the TimeLine of changing the property of the Window in the Blend and just activate the animation in the .cs code.