xamarin.forms - 如何在退出 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”打印出来。
解决方案
经过一番挖掘,我发现应用关闭确认实际上是一项受限功能,您必须在应用程序清单中声明。在解决方案资源管理器中右键单击该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()
例如意味着立即应用程序的“硬杀”。
推荐阅读
- python - 根据频率扩展数据集
- ios - 不兼容的块指针类型 - Objective-c
- python - 如何从python中获取xml标签中的单个元素
- postgresql - 如何在文本中查询一系列单词,但不一定在 Postgres 中紧随其后
- c# - 如何以管理员身份运行 Azure Function?
- angular - `ERROR RangeError: Maximum call stack size exceeded` - 无法从嵌套项目加载页面
- javascript - 在请求标头中传递证书文件时标头太长错误
- swift - 没有标识符错误iOS故事板的segue
- python - Picking Shape Keras-ValueError: 预期的 dense_1_input 的形状为 (8,) 但得到的数组的形状为 (13,)
- c# - 更新同一型号网络适配器之一的驱动程序