WPF故事板初学者问题

时间:2009-05-26 12:43:25

标签: .net wpf animation storyboard

我正在编写我的第一个WPF应用程序,并且我正在尝试在表单关闭时实现淡入淡出动画。我遇到了这个问题Fading out a wpf window on close,它展示了如何制作淡出动画,但我似乎无法让它发挥作用。我在我的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>

然后我有这个事件处理程序:

    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();
        }
    }

但是当调用sb.Begin()方法时,我得到了这个例外:

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

如上所述,这是我第一次尝试使用WPF,所以我很喜欢在表单关闭时添加淡出功能。

1 个答案:

答案 0 :(得分:4)

您需要在StoryBoard动画中添加目标UI元素,否则无法将动画应用到。

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