Question

I currently have a set of buttons that I would like to set triggers so that each one will perform the same animation. Is there a way in XAML to 'pass' the target to the storyboard so that I don't have to rewrite the storyboard each time for each target?

Was it helpful?

Solution

If you don't set an explicit target, the target should be the element to which the animation is being applied. I would define a style with the trigger/animation on it and apply the style to those particular buttons that you want to exhibit this behavior. For example:

<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>

And then on each button you want to behave this way:

<Button Style="{StaticResource MyButtonStyle}" ... />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top