此示例演示如何对样式中的属性进行动画处理。 在样式中进行动画处理时,只能直接针对定义样式的框架元素。 要定位可冻结对象,必须从样式元素的某个属性中导航。
在下面的示例中,多个动画在样式中定义并应用于一个 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 动画不会引发异常;动画只会以无提示方式失败。
有关情节板目标语法的详细信息,请参阅 情节板概述。 有关动画的详细信息,请参阅 动画概述。 有关样式的详细信息,请参阅 样式设置和模板化。