使 UIElement 逐渐进入视野并从视野中逐渐消失
此示例演示如何使用 Silverlight 动画通过对属性值进行动画处理,使 Rectangle 逐渐进入视野并从视野中逐渐消失。本示例使用 DoubleAnimation(一种生成 Double 值的动画类型)对 Rectangle 的 Opacity 属性进行动画处理。因此,Rectangle 将逐渐进入视野并逐渐从视野中消失。若要查看您将演练的动画的预览,请单击下面的链接来运行示例,然后单击矩形开始运行动画。
示例的第一部分创建一个 Rectangle 元素,并将其显示在 StackPanel 中。
<StackPanel>
<Rectangle MouseLeftButtonDown="Mouse_Clicked"
x:Name="MyAnimatedRectangle"
Width="100" Height="100" Fill="Blue" />
</StackPanel>
创建 DoubleAnimation
由于 属性的类型是 Double,因此需要一个生成 Double 值的动画。DoubleAnimation 就是这样一种动画;它可以创建两个 Double 值之间的过渡。若要指定 DoubleAnimation 的起始值,可设置其 From 属性。若要指定其终止值,可设置其 To 属性。
<DoubleAnimation From="1.0" To="0.0" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever"/>
创建演示图板
若要向对象应用动画,请创建 对象并使用 TargetName 和 TargetProperty 附加属性指定要进行动画处理的对象和属性。
<Storyboard> <DoubleAnimation Storyboard.TargetName="MyAnimatedRectangle" From="1.0" To="0.0" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever" /> </Storyboard>
将演示图板与事件相关联
此时您已经指定了动画的目标对象以及动画的行为方式;接下来您需要指定何时开始播放动画。可以使用事件执行此操作。
<StackPanel> <StackPanel.Resources> <!-- Animates the rectangle's opacity. --> <Storyboard x:Name="myStoryboard"> <DoubleAnimation Storyboard.TargetName="MyAnimatedRectangle" Storyboard.TargetProperty="Opacity" From="1.0" To="0.0" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever" /> </Storyboard> </StackPanel.Resources><Rectangle MouseLeftButtonDown="Mouse_Clicked" x:Name="MyAnimatedRectangle" Width="100" Height="100" Fill="Blue" /></StackPanel>
c#
// When the user clicks the Rectangle, the animation // begins. private void Mouse_Clicked(object sender, MouseEventArgs e) { myStoryboard.Begin(); }
完整的示例
下面的示例演示了完整的 XAML 标记,这些标记用于创建在加载时逐渐进入视野并从视野中逐渐消失的矩形。
<UserControl x:Class="animation_ovw_intro.Page" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="400" Height="300"> <StackPanel> <StackPanel.Resources> <!-- Animates the rectangle's opacity. --> <Storyboard x:Name="myStoryboard"> <DoubleAnimation Storyboard.TargetName="MyAnimatedRectangle" Storyboard.TargetProperty="Opacity" From="1.0" To="0.0" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever" /> </Storyboard> </StackPanel.Resources> <Rectangle MouseLeftButtonDown="Mouse_Clicked" x:Name="MyAnimatedRectangle" Width="100" Height="100" Fill="Blue" /> </StackPanel> </UserControl>
C#
private void Mouse_Clicked(object sender, MouseEventArgs e) { myStoryboard.Begin(); }