WPF MVVM: How to close a window

后端 未结 21 1813
后悔当初
后悔当初 2020-12-04 08:19

I have a Button that closes my window when it\'s clicked:


21条回答
  •  生来不讨喜
    2020-12-04 08:43

    The solution to close a window in wpf that that worked for me is not answered here so i thought i would add my solution too.

            private static Window GetWindow(DependencyObject sender)
            {
                Window window = null;
                if (sender is Window)
                    window = (Window)sender;
                if (window == null)
                    window = Window.GetWindow(sender);
                return window;
            }
            private void CloseWindow(object sender, RoutedEventArgs e)
            {
                var button = (Button)sender as DependencyObject;
    
                Window window = GetWindow(button);
                    if (window != null)
                        window.Close();
                       // window.Visibility = Visibility.Hidden; 
               // choose between window.close or set window.visibility to close or hide the window.
    
                //            }
            }
    
    

    Add CloseWindow event to the button in you window as following.

提交回复
热议问题