sondlerd sondlerd - 1 year ago 139
C# Question

WPF Fade Out on a control

In my WPF app, I have a feedback control that I want to appear after a user action completes (save data, delete...). The visibility is set to Hidden to begin and style set to the animateFadeOut style defined as a resource (see below). Then I want to set the text and control Visibility to visible in my C# code and have the feedback control display the message and fade out after 5 seconds and remain hidden (Visibility.Hidden).

The following XAML works the first time I call control.Visiblity= Visibility.Visible but the control doesn't reappear the second time. I figure that is because the animation is still running, which has control over the feedback control. I then tried to set FillBehavior to "Stop" but that just made the control visible again and I want it hidden. Then, with FillBehavior="Stop", I tried to set a trigger "when Opacity = 0, set the Visibility to Hidden". The trigger didn't seem to fire and I was left with the visible control once more after the animation completed.

Please help point out what I am doing wrong here.

Alternatively, if you can suggest a better way to display a control that fades after 5 seconds and can be called over and over, I would appreciate it.


<Style TargetType="{x:Type FrameworkElement}" x:Key="animateFadeOut">
<Trigger Property="Visibility" Value="Visible">
<BeginStoryboard >
<DoubleAnimation BeginTime="0:0:5.0" Storyboard.TargetProperty="Opacity"
From="1.0" To="0.0" Duration="0:0:0.5"/>

Answer Source

The problem is that after your animation completes your control still has Visibility=Visible, so it cannot be entered again.
I would rather use animation that does the whole thing, first shows the control, then hides it.

<Storyboard x:Key="animate">
    <ObjectAnimationUsingKeyFrames BeginTime="0:0:0" Storyboard.TargetProperty="Visibility">
        <DiscreteObjectKeyFrame KeyTime="0">
    <DoubleAnimation BeginTime="0:0:0.0" Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:0.2"/>
    <DoubleAnimation BeginTime="0:0:5.0" Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:0.5"/>
    <ObjectAnimationUsingKeyFrames BeginTime="0:0:5.5" Storyboard.TargetProperty="Visibility">
        <DiscreteObjectKeyFrame KeyTime="0">

And use it as follows:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download