问题描述
我正在编写我的第一个WPF应用程序,并且试图在窗体关闭时实现淡入淡出动画。我碰到了这个问题,该窗口显示如何制作淡出动画,但是我似乎无法正常工作。我的XAML中包含以下内容:
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();
}
}
但是当 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'.
如上所述,这是我第一次参加WPF,所以我很困惑自己需要做的事情在窗体关闭时添加淡出。
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.
推荐答案
您需要向StoryBoard动画中添加目标UI元素
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>
这篇关于WPF故事板初学者问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!