异步无法按 Windows Phone 8.1 的后退键
async not working on pressing back key of Windows Phone 8.1
private async void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
var msg = new MessageDialog("Confirm Close");
var okBtn = new UICommand("OK");
var cancelBtn = new UICommand("Cancel");
msg.Commands.Add(okBtn);
msg.Commands.Add(cancelBtn);
IUICommand result = await msg.ShowAsync();
}
主要问题是按下后退按钮时,消息会显示 1-2 秒,然后应用会关闭。
怎么办?
我认为异步工作正常,您没有将 e.Handeled 设置为 true,这意味着进一步 BackPressed事件被处理并且应用程序退出。像这样尝试:
private async void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
e.Handled = true;
var msg = new MessageDialog("Confirm Close");
var okBtn = new UICommand("OK");
var cancelBtn = new UICommand("Cancel");
msg.Commands.Add(okBtn);
msg.Commands.Add(cancelBtn);
IUICommand result = await msg.ShowAsync();
}
另请记住,您的应用必须能够通过 BackButton 退出,因此必须以某种方式修改上面的代码。
试试这个代码:
var messgeDialog = new MessageDialog("Are you sure you want to close", "Are you sure?");
messgeDialog.Commands.Add(new UICommand("Yes"));
messgeDialog.Commands.Add(new UICommand("No"));
messgeDialog.DefaultCommandIndex = 0;
messgeDialog.CancelCommandIndex = 1;
var result = await messgeDialog.ShowAsync();
if (result.Label.Equals("Yes"))
{
//Do something when a user pressed yes
}
else
{
//User pressed no
}
private async void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
var msg = new MessageDialog("Confirm Close");
var okBtn = new UICommand("OK");
var cancelBtn = new UICommand("Cancel");
msg.Commands.Add(okBtn);
msg.Commands.Add(cancelBtn);
IUICommand result = await msg.ShowAsync();
}
主要问题是按下后退按钮时,消息会显示 1-2 秒,然后应用会关闭。 怎么办?
我认为异步工作正常,您没有将 e.Handeled 设置为 true,这意味着进一步 BackPressed事件被处理并且应用程序退出。像这样尝试:
private async void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
e.Handled = true;
var msg = new MessageDialog("Confirm Close");
var okBtn = new UICommand("OK");
var cancelBtn = new UICommand("Cancel");
msg.Commands.Add(okBtn);
msg.Commands.Add(cancelBtn);
IUICommand result = await msg.ShowAsync();
}
另请记住,您的应用必须能够通过 BackButton 退出,因此必须以某种方式修改上面的代码。
试试这个代码:
var messgeDialog = new MessageDialog("Are you sure you want to close", "Are you sure?");
messgeDialog.Commands.Add(new UICommand("Yes"));
messgeDialog.Commands.Add(new UICommand("No"));
messgeDialog.DefaultCommandIndex = 0;
messgeDialog.CancelCommandIndex = 1;
var result = await messgeDialog.ShowAsync();
if (result.Label.Equals("Yes"))
{
//Do something when a user pressed yes
}
else
{
//User pressed no
}