I am currently developing a wpf c# application. I have added to event triggers to the xaml of the form to fade in when the window loads and fades out when the window closes.
just try this sample
<Window x:Class="FadeInAndOutWindow.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" Closing="Window_Closing" x:Name="winHelp">
<Window.Triggers>
<EventTrigger RoutedEvent="Window.Loaded">
<BeginStoryboard>
<Storyboard Name="FormFade">
<DoubleAnimation Name="FormFadeAnimation"
Storyboard.TargetName="winHelp"
Storyboard.TargetProperty="(Window.Opacity)"
From="0.0"
To="1.0"
Duration="0:0:1"
AutoReverse="False"
RepeatBehavior="1x" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="Window.Unloaded">
<BeginStoryboard>
<Storyboard Name="FormFadeOut"
Completed="FormFadeOut_Completed">
<DoubleAnimation Name="FormFadeOutAnimation"
Storyboard.TargetName="winHelp"
Storyboard.TargetProperty="(Window.Opacity)"
From="1.0"
To="0.0"
Duration="0:0:1"
AutoReverse="False"
RepeatBehavior="1x" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Window.Triggers>
<Grid>
</Grid>
namespace FadeInAndOutWindow
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private bool closeCompleted = false;
private void FormFadeOut_Completed(object sender, EventArgs e)
{
closeCompleted = true;
this.Close();
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!closeCompleted)
{
FormFadeOut.Begin();
e.Cancel = true;
}
}
}
}
H.B. solution is good but don't close effectively the window because Close() call window_Closing and loop. Here my working solution:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
AlreadyFaded = false;
}
bool AlreadyFaded;
private void window_Closing(object sender, CancelEventArgs e)
{
if (!AlreadyFaded)
{
AlreadyFaded = true;
e.Cancel = true;
var anim = new DoubleAnimation(0, (Duration)TimeSpan.FromSeconds(1));
anim.Completed += new EventHandler(anim_Completed);
this.BeginAnimation(UIElement.OpacityProperty, anim);
}
}
void anim_Completed(object sender, EventArgs e)
{
Close();
}
Unloaded is not a suitable event for this, i'm not sure if this event can even occur for windows. You need to handle Closing
, prevent it from actually closing, start an animation and close it when the Completed
event of the animation occurs.
e.g.
<Window ...
Closing="Window_Closing">
private void Window_Closing(object sender, CancelEventArgs e)
{
Closing -= Window_Closing;
e.Cancel = true;
var anim = new DoubleAnimation(0, (Duration)TimeSpan.FromSeconds(1));
anim.Completed += (s, _) => this.Close();
this.BeginAnimation(UIElement.OpacityProperty, anim);
}