Search code examples
c#wpfanimationstyles

c# wpf animating opacity in visibility trigger


I am creating a Style containing Animation's, which can then be inherited to specific control styles, which are applied automatically.

Actually I'm struggling on implementing a simple Animation:

  • When Visibility is changed to Visible, Opacity is changed from 0 to 1
  • When Visibility is changed to something else than visible, Opacity is doing the inverse thing

So far I got:

<Style x:Key="BaseAnimationsStyle">
    <Style.Triggers>
        <Trigger Property="FrameworkElement.Visibility" Value="Visible">
            <Trigger.EnterActions> <!-- this works -->
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetProperty="Opacity" To="1" Duration="0:0:0.5" />
                    </Storyboard>
                </BeginStoryboard>
            </Trigger.EnterActions>
            <Trigger.ExitActions><!-- this doesn't -->
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetProperty="Opacity" To="0" Duration="0:0:0.5" />
                    </Storyboard>
                </BeginStoryboard>
            </Trigger.ExitActions>
        </Trigger>
    </Style.Triggers>
</Style>

If the above Style is set on a control it then has the following behaviour:

When the control's Visibility is set to Visible the transition is working correctly, meaning it is fading in.

Issue: When the control's Visibility is set to Hidden (or even Collapsed), the control will be hidden instantly without fading.

My guess is, that there is some default behaviour to be overridden of how FrameworkElement's deal with Visibility-Changes.


Solution

  • Setting the Visibility property to Collapsed or Hidden will make the element invisible right away but instead of setting the Visibility property you could set some attached property of yours and then animate the Opacity property to fade out the element. Please refer to the following link for more information and an example.

    WPF: How To Animate Visibility Property?: http://blogs.microsoft.co.il/arik/2010/02/08/wpf-how-to-animate-visibility-property/ https://www.codeproject.com/Articles/57175/WPF-How-To-Animate-Visibility-Property

    WPF Fade Animation