WPF Setting Storyboard target in XAML

10,002

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}" ... />
Share:
10,002
jwarzech
Author by

jwarzech

Former C# and Ruby developer, curious about all technologies/platforms.

Updated on June 16, 2022

Comments

  • jwarzech
    jwarzech almost 2 years

    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?

  • jwarzech
    jwarzech over 14 years
    Awesome! I am just starting to learn WPF and didn't think of applying a style with the associated trigger and animation. Thanks for the help!