WPF Storyboard beginner problem

99封情书 提交于 2020-01-15 10:21:21

问题


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 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:


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>


来源:https://stackoverflow.com/questions/910488/wpf-storyboard-beginner-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!