WPF关闭时执行代码

Sty*_*s05 20 wpf execute event-handling

我不熟悉使用事件处理程序,我想知道是否有人或者可以指示我使用一些代码来演示如何使用将在Close/Closed事件上执行代码的事件处理程序?

我知道这可以做到,因为这个回答的问题:

在WPF表单上运行代码关闭

但我需要一些方向.

谢谢=)

Cle*_*ens 38

就是这个XAML

<Window ... Closing="Window_Closing" Closed="Window_Closed">
    ...
</Window>
Run Code Online (Sandbox Code Playgroud)

ClosingClosed事件的代码

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    ...
}

private void Window_Closed(object sender, EventArgs e)
{
    ....
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*n P 24

如果你想从后面的代码中完成所有操作,请将它放在windows .cs文件中

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Closed += new EventHandler(MainWindow_Closed);
        }

        void MainWindow_Closed(object sender, EventArgs e)
        {
            //Put your close code here
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想参与xaml并参与代码,请在xaml中执行此操作

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Closed="MainWindow_Closed">
    <Grid>

    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

这在.cs

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        void MainWindow_Closed(object sender, EventArgs e)
        {
            //Put your close code here
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以上示例您可以应用于xaml应用程序中的任何表单.您可以有多个表单.如果要为整个应用程序退出过程应用代码,请将app.xaml.cs文件修改为此文件

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnExit(ExitEventArgs e)
        {
            try
            {
                //Put your special code here
            }
            finally
            {
                base.OnExit(e);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)