我目前有一组按钮,我想设置触发器,以便每个按钮执行相同的动画。是否有一种方法在XAML 中将目标“传递”到故事板,这样我就不必每次都为每个目标重写故事板?
答案 0 :(得分:15)
如果未设置显式目标,则目标应为要应用动画的元素。我将定义一个带有触发器/动画的样式,并将样式应用于要显示此行为的特定按钮。例如:
<Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
<Style.Resources>
<Storyboard x:Key="OnMouseEnterStoryboard">
<DoubleAnimation BeginTime="00:00:00" Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)" To="180" />
</Storyboard>
<Storyboard x:Key="OnMouseLeaveStoryboard">
<DoubleAnimation BeginTime="00:00:00" Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)" To="0" />
</Storyboard>
</Style.Resources>
<Style.Triggers>
<EventTrigger RoutedEvent="Mouse.MouseLeave">
<RemoveStoryboard BeginStoryboardName="OnMouseEnterStoryboard_BeginStoryboard"/>
<BeginStoryboard x:Name="OnMouseLeaveStoryboard_BeginStoryboard" Storyboard="{StaticResource OnMouseLeaveStoryboard}"/>
</EventTrigger>
<EventTrigger RoutedEvent="Mouse.MouseEnter">
<BeginStoryboard x:Name="OnMouseEnterStoryboard_BeginStoryboard" Storyboard="{StaticResource OnMouseEnterStoryboard}"/>
<RemoveStoryboard BeginStoryboardName="OnMouseLeaveStoryboard_BeginStoryboard"/>
</EventTrigger>
</Style.Triggers>
<Setter Property="RenderTransformOrigin" Value="0.5,0.5"/>
<Setter Property="RenderTransform">
<Setter.Value>
<RotateTransform/>
</Setter.Value>
</Setter>
</Style>
然后在每个按钮上你想要这样做:
<Button Style="{StaticResource MyButtonStyle}" ... />