views:

815

answers:

2

I'm writing my first WPF application and I'm trying to implement a fade animation when the form closes. I came across this question http://stackoverflow.com/questions/867656/fading-out-a-wpf-window-on-close which shows how to make a fade-out animation but I can't seem to get it working. I have this in my XAML:

<Window.Resources>
    <Storyboard Name="FadeOutStoryboard" x:Key="FadeOutStoryboard" Completed="FadeOutStoryboard_Completed">
        <DoubleAnimation Storyboard.TargetProperty="Window.Opacity" From="1" To="0" Duration="0:0:2" FillBehavior="HoldEnd" />
    </Storyboard>
</Window.Resources>

And I then have this event handler:

    private bool doneFade;
    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        if (!doneFade)
        {
            e.Cancel = true;
            Storyboard sb = (Storyboard)this.FindResource("FadeOutStoryboard");
            sb.Begin();
        }
    }

But when the sb.Begin() method is called I get this exception:

System.InvalidOperationException: No target was specified for 'System.Windows.Media.Animation.DoubleAnimation'.

As stated this is my first attempt at WPF so I'm rather comfused at what I need to do to add the fade-out when the form is closing.

+1  A: 

You need to add a target UI element to your StoryBoard animation otherwise it's got nothing to apply the animation to.

<Storyboard Name="FadeOutStoryboard" x:Key="FadeOutStoryboard" Completed="FadeOutStoryboard_Completed">        
     <DoubleAnimation Storyboard.TargetName="myWindow" Storyboard.TargetProperty="Window.Opacity" From="1" To="0" Duration="0:0:2" FillBehavior="HoldEnd" />    
</Storyboard>
sipwiz
A: 

I cannot find the property Storyboard.TargetName in the doubleanimation class, how to do in code?

pino