The problem of a novice WPF designer
I am writing my first WPF application and I am trying to implement a fade out animation when a form closes. I came across this question Wpf window fade out on close which shows how to make a fade out animation, but I can't get it to work. 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 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 method is called sb.Begin()
, I get this exception:
System.InvalidOperationException: No target was specified for 'System.Windows.Media.Animation.DoubleAnimation'.
As said, this is my first attempt at WPF, so I rather agree on what I need to do to add a fade when the form is closed.
+1
a source to share
1 answer
You need to add the target UI element to your StoryBoard animation, otherwise it would have nothing to animate.
<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>
+3
a source to share