应用程序层级关系
生命周期
1.vs通用应用程序 c# ,删除默认xaml,并添加空白页 BlankPage1
1.1 将BlankPage1属性设置如下
2.运行项目 ,正常如下 ,如果出错,删除项目文件夹中的obj文件夹
3.尝试添加一个空白页
3.1给这个空白页添加一个椭圆
<Grid>
<Ellipse Width="300" Height="300" Fill="Green" HorizontalAlignment="Center" VerticalAlignment="Center"></Ellipse>
</Grid>
4.重写入口程序中OnLanched方法,注意看注释
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板
namespace App3
{
/// <summary>
/// 可用于自身或导航至 Frame 内部的空白页。
/// </summary>
public sealed partial class BlankPage1 : Application
{
public BlankPage1()
{
this.InitializeComponent();
}
protected override void OnLaunched(LaunchActivatedEventArgs args)
//重写程序的onLangched方法
{
Frame rootFrame = null;
/*
Window.Current.Content as Frame;
window当前应用程序
Current 当前窗口
content 当前窗口内容
*/
rootFrame = Window.Current.Content as Frame;
if ( rootFrame == null) {
rootFrame = new Frame();
Window.Current.Content = rootFrame;// 如果窗口为空,赋值
}
rootFrame.Navigate(typeof(BlankPage2)); //将页面导航到 BlankPage2
Window.Current.Activate();//激活当前窗口
}
}
}
运行结果如下
4.1 方法二 导航至页面
protected override void OnLaunched(LaunchActivatedEventArgs args){
//重写程序的onLangched方法
//方法二 显示BlankPage2
BlankPage2 page2 = new BlankPage2();
Window.Current.Content = page2;
Window.Current.Activate();//激活当前窗口
}
5.Application追踪查看 生命周期方法
5.1 添加挂起和恢复事件 ,挂起一般会保存数据
public BlankPage1()
{
this.InitializeComponent();
this.Suspending += OnSuspending;//添加挂起事件
this.Resuming += OnResuming;//添加恢复事件
}
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
System.Diagnostics.Debug.WriteLine("挂起");
await new Windows.UI.Popups.MessageDialog("z正在挂起").ShowAsync();
}
private async void OnResuming(object sender, object e)
{
System.Diagnostics.Debug.WriteLine("恢复");
await new Windows.UI.Popups.MessageDialog("正在恢复").ShowAsync();
}
要测试挂起程序,需要再如下位置触发
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
// System.Diagnostics.Debug.WriteLine("挂起");
var d = e.SuspendingOperation.GetDeferral();//拖延挂起时间
var setting = Windows.Storage.ApplicationData.Current.LocalSettings;//保存到注册表
setting.Values["v"] = State;
// await new Windows.UI.Popups.MessageDialog("z正在挂起").ShowAsync();
d.Complete();//结束挂起时间,目的让程序保存完数据
}