Fading out a wpf window on close

前端 未结 5 879

I want to fade a window in/out in my application.
Fading in occurs on Window.Loaded and I wanted to fade out on close (Window.Closed or

5条回答
  •  情书的邮戳
    2020-12-14 02:48

    This is even simpler and shorter. Add a behavior as follows:

    public class WindowClosingBehavior : Behavior
        {
            protected override void OnAttached()
            {
                AssociatedObject.Closing += AssociatedObject_Closing;
            }
    
            private void AssociatedObject_Closing(object sender, System.ComponentModel.CancelEventArgs e)
            {
                Window window = sender as Window;
                window.Closing -= AssociatedObject_Closing;
                e.Cancel = true;
                var anim = new DoubleAnimation(0, (Duration)TimeSpan.FromSeconds(0.5));
                anim.Completed += (s, _) => window.Close();
                window.BeginAnimation(UIElement.OpacityProperty, anim);
            }
            protected override void OnDetaching()
            {
                AssociatedObject.Closing -= AssociatedObject_Closing;
            }
        }
    

    Then in your window add a reference :

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:wt="clr-namespace:Desktop.Themes.WindowTask;assembly=Desktop.Themes"
    

    Insert the behavior:

    
         
    
    

提交回复
热议问题