WPF入门(三)--事件Event调用

1、WPF应用程序的关闭

WPF应用程序的关闭只有在应用程序的 Shutdown 方法被调用时,应用程序才停止运行。 ShutDown 是隐式或显式发生,可以通过指定 ShutdownMode 的属性值来进行设置。

WPF入门(三)--事件Event调用_第1张图片

 对ShutdownMode选项的更改,可以直接在App.xaml中更改,如下代码。


    

    

1.在代码文件(App.xaml.cs)中修改ShutdownMode选项,但必须注意这个设置要写在app.Run()方法之前 ,如下代码。

app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
    app.Run(win);

在应用程序中添加事件的方式有如下三种。

这里写图片描述


    
    

3、在App.xaml.cs文件的代码如下:

第一种方式--属性界面事件录入(类似Winform事件):

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApp1
{
    /// 
    /// App.xaml 的交互逻辑
    /// 
    public partial class App : Application
    {
        private void Application_Activated(object sender, EventArgs e)

        {
        }
        private void Application_Exit(object sender, ExitEventArgs e)
        {
        }
    }
}

4.在使用以上方式添加事件之后,如果在Visual Studio中按F5 执行应用程序时,报以下错误“不包含适合于入口点的静态‘Main’方法”。这个错误是由于Visual Studio把项目文件(*.csproj--配置信息注记录文件)中原来自动生成的app.xaml相关的定义进行了修改。具体区别如下:
4.1直接新建的WPF项目中的有关App.xaml的定义如下:


      MSBuild:Compile
      Designer
    

4.2Visual Studio把修改后的App.xaml的配置代码如下


      Designer
      MSBuild:Compile
    

 第一段代码中App.xaml在项目文件里面用ApplicationDefinition标签定义。第二段代码中App.xaml在项目文件里面用Page标签定义,这种定义是指App.xaml只是一个页面而已。
  因此,只需要把项目文件中将App.xaml的配置由Page修改成ApplicationDefinition即可。

第二种方式
1、可以像是在WinForm中的Program类中写Main方法一样,在WPF中一样可以自定义一个app类中写main及其他相关事件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApp1
{
    class App
    {
        [STAThread]
        static void Main()
        {
            // 定义Application对象作为整个应用程序入口 
            Application app = new Application();
            MainWindow win = new MainWindow();
            app.ShutdownMode = ShutdownMode.OnMainWindowClose;
            app.MainWindow = win;
            //是必须的,否则无法显示窗体      
            win.Show();
            app.Run();
            app.Activated += app_Activated;
            app.Exit += app_Exit;
        }
 static void app_Activated(object sender, EventArgs e)
 {
     throw new NotImplementedException();
 }
 static void app_Exit(object sender, ExitEventArgs e)
 {
     throw new NotImplementedException();
 }
    }
}

第三种方式--XAML 界面手写录入事件名称
在App.xaml界面中,如下图位置1处,输入Exit事件名称,Visual Studio 2013会弹出一个菜单“新建事件处理程序”,双击这个菜单,Visual Studio 2019就会自动创建一个“Application_Exit”事件,如下图位置2处。

这里写图片描述

五、WPF应用程序生存周期

WPF应用程序的生命周期与执行顺序,用MSDN上的一张图片进行说明。下图显示了窗口的生存期中的主体事件的顺序。

这里写图片描述

你可能感兴趣的:(WPF教程,wpf)