如何以某种风格制作动画
此示例演示如何对样式中的属性进行动画处理。 在样式中进行动画处理时,只能直接针对定义样式的框架元素。 若要以可冻结对象为目标,必须从样式元素的属性“向下点”。
在以下示例中,多个动画已定义在样式中,并被应用于 Button。 当用户将鼠标移到按钮上时,它会从不透明变为部分半透明,并如此反复变化。 当用户将鼠标从按钮上移开时,它将变得完全不透明。 单击按钮后,其背景色将从橙色更改为白色,然后再次返回。 由于用于绘制按钮的 SolidColorBrush 不能直接被定位,可以通过访问按钮的 Background 属性来获取。
例
<!-- StyleStoryboardsExample.xaml
This example shows how to create storyboards in a style. -->
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowTitle="Storyboards in Styles Example" Background="White">
<Page.Resources>
<!-- Defines a Button style. -->
<Style TargetType="{x:Type Button}" x:Key="MyButtonStyle">
<Setter Property="Button.Background">
<Setter.Value>
<SolidColorBrush Color="Orange" />
</Setter.Value>
</Setter>
<Style.Triggers>
<!-- Animates the button's opacity on mouse over. -->
<EventTrigger RoutedEvent="Button.MouseEnter">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Button.Opacity)"
From="1.0" To="0.5" Duration="0:0:0.5" AutoReverse="True"
RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<!-- Returns the button's opacity to 1 when the mouse leaves. -->
<EventTrigger RoutedEvent="Button.MouseLeave">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Button.Opacity)"
To="1" Duration="0:0:0.1" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<!-- Changes the button's color when clicked.
Notice that the animation can't target the
SolidColorBrush used to paint the button's background
directly. The brush must be accessed through the button's
Background property. -->
<EventTrigger RoutedEvent="Button.Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation
Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)"
From="Orange" To="White" Duration="0:0:0.1" AutoReverse="True" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
</Style>
</Page.Resources>
<StackPanel Margin="20">
<Button Style="{StaticResource MyButtonStyle}">Click Me</Button>
</StackPanel>
</Page>
请注意,在样式中进行动画处理时,可以将不存在的对象作为目标。 例如,假设您的样式使用 SolidColorBrush 设置按钮的背景属性,但在某些时候,该样式被覆盖,按钮的背景设置为 LinearGradientBrush。 尝试对 SolidColorBrush 进行动画处理不会引发异常;动画只会以无提示方式失败。
有关 Storyboard 定位语法的详细信息,请参阅 Storyboard 概述。 有关动画的详细信息,请参阅 动画概述。 有关样式的详细信息,请参阅 样式设计和模板设置。