我目前有一组按钮,希望设置触发器,以便每个按钮都执行相同的动画。 XAML 中是否存在将目标“传递”到 Storyboard 的方式,这样我就不必每次为每个目标重写 Storyboard 吗?

最佳答案

如果未设置显式目标,则目标应该是要对其应用动画的元素。我将定义一个带有触发器/动画的样式,然后将该样式应用于您要表现出这种行为的那些特定按钮。例如:

<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}" ... />

关于.net - XAML中的WPF设置 Storyboard 目标,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1639890/

10-13 06:55