Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close WPF window after animation

Tags:

animation

wpf

I'm using an animation to cause a window to fade out of focus, then close.

However, the close event occurs immediately after the animation.

What is the simplest way to make the window close after the animation?

In the following code, MainWindow is the second window that is being opened. This method is called when a button is clicked in the first window.

private void CloseMethod(object sender, RoutedEventArgs e)
{
    MainWindow win = new MainWindow();
    win.Show();
    DoubleAnimation animation = new DoubleAnimation()
    {
        From = 1.0,
        To = 0.0,
        Duration = new Duration(TimeSpan.FromSeconds(2))
    };
    this.BeginAnimation(Window.OpacityProperty, animation);
    this.Close();
}
like image 344
Aaron Thomas Avatar asked Jan 18 '26 06:01

Aaron Thomas


1 Answers

I accepted Omar's answer, but for purposes of learning also wanted to point out that if a Storyboard is used, the Completed event can be used to call a method to close a window, after the animation in the storyboard has occurred. Coupled with a Button.Click method, this can also achieve the desired effect:

<Button Foreground="Red" ToolTip="Close this window." Click="ShowMainWin">
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation
                        Storyboard.TargetName="EntireWindow"
                        Storyboard.TargetProperty="Opacity"
                        From="1.0" To="0.0"
                        Duration="0:0:0.5"
                        Completed="CloseMethod"></DoubleAnimation>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Button.Triggers>
    Close Window</Button>

And, in the code, I define "ShowMainWin" and "CloseMethod".

"ShowMainWin" happens when the button is clicked, causing the second window to open immediately. The animation in the Storyboard runs, causing the first window to fade away. Once the animation is complete, "CloseMethod" is called, causing the first window to close:

private void ShowMainWin(object sender, RoutedEventArgs e)
{
    MainWindow win = new MainWindow();
    win.Show();
}

public void CloseMethod(object sender, EventArgs e)
{
    this.Close();
}
like image 66
Aaron Thomas Avatar answered Jan 19 '26 20:01

Aaron Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!