Home » c# » c# – WPF form opacity fade animation not finishing if less then 1 second-Exceptionshub

c# – WPF form opacity fade animation not finishing if less then 1 second-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have a form that I would like to have fade to 70% opacity unless the mouse if over the form the code I have only works properly if I set the animation time to 1 second. Anything less then that and the animation seems to stop before getting back to 100% opacity.

<Window.Resources>
    <Style TargetType="local:MainWindow">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Trigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard
                                Storyboard.TargetProperty="(Window.Opacity)"
                                Duration="0:0:0.3">
                            <DoubleAnimation To="1" />
                        </Storyboard>
                    </BeginStoryboard>
                </Trigger.EnterActions>
                <Trigger.ExitActions>
                    <BeginStoryboard>
                        <Storyboard
                                Storyboard.TargetProperty="(Window.Opacity)"
                                Duration="0:0:0.3">
                            <DoubleAnimation To=".70" />
                        </Storyboard>
                    </BeginStoryboard>
                </Trigger.ExitActions>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>
How to&Answers:

Storyboard.TargetProperty and Duration must be set on the animations, not on the Storyboard.

If you set the Duration on the Storyboard, the animations run for their default Duration of 1 second.

<Trigger Property="IsMouseOver" Value="True">
    <Trigger.EnterActions>
        <BeginStoryboard>
            <Storyboard>
                <DoubleAnimation
                    Storyboard.TargetProperty="Opacity"
                    To="1" Duration="0:0:0.3"/>
            </Storyboard>
        </BeginStoryboard>
    </Trigger.EnterActions>
    <Trigger.ExitActions>
        <BeginStoryboard>
            <Storyboard>
                <DoubleAnimation
                    Storyboard.TargetProperty="Opacity"
                    To=".7" Duration="0:0:0.3" />
            </Storyboard>
        </BeginStoryboard>
    </Trigger.ExitActions>
</Trigger>