首页 > 解决方案 > 如何在退出 UWP Xamarin 表单时提示确认消息?

问题描述

目标实现:
- 提示确认消息“您确认退出吗? ”,选项“”和“取消

我一直在寻找一种方法来实现上面写的目标。我尝试了以下代码:

Windows.UI.Core.Preview.SystemNavigationManagerPreview.GetForCurrentView().CloseRequested += async (sender, args) =>
{
        args.Handled = true;
        var dialog = new MessageDialog("Are you confirm to exit?", "Exit");
        System.Diagnostics.Debug.WriteLine("CLOSE");            
};

我在MainPage.xaml.cs中编写了上面的代码,但是这段代码似乎对我不起作用,我没有在调试输出中看到“CLOSE”打印出来。

标签: xamarin.formsuwpdialog

解决方案


经过一番挖掘,我发现应用关闭确认实际上是一项受限功能,您必须在应用程序清单中声明。在解决方案资源管理器中右键单击该Package.appxmanifest文件,然后选择查看代码

在打开的 XML 文件中,首先在根Package元素中添加以下命名空间:

xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"

现在找到Capabilities添加confirmAppClose功能的部分:

<Capabilities>
   <Capability Name="internetClient" />
   <rescap:Capability Name="confirmAppClose" />
</Capabilities>

另外,请注意,如果要显示,则必须使用延迟,以便系统在检查属性之前MessageDialog等待await完成:Handled

var deferral = e.GetDeferral();           
var dialog = new MessageDialog("Are you sure you want to exit?", "Exit");
var confirmCommand = new UICommand("Yes");
var cancelCommand = new UICommand("No");
dialog.Commands.Add( confirmCommand);            
dialog.Commands.Add(cancelCommand);
dialog.CancelCommandIndex = 1;
dialog.DefaultCommandIndex = 1;
if (await dialog.ShowAsync() == cancelCommand)
{
    //cancel close by handling the event
    e.Handled = true;                
}
deferral.Complete();

与仅手动终止应用程序并将事件设置为Handled每次都相比,这种方法的优势在于,在这种情况下,应用程序首先经历暂停生命周期事件,这允许您保存任何未保存的更改,而Application.Terminate()例如意味着立即应用程序的“硬杀”。


推荐阅读