我正在使用Windows Phone 8.1应用。我想在用户按回键时显示消息。我知道代码,但出了点问题。 Visual Studio在MessageBox,MessageBoxResult。
下显示红线如何在Windows Phone 8.1中显示消息?我认为在WP7操作系统之后它已经改变了。
这是我的代码示例。
public MainPage()
{
this.InitializeComponent();
progRing.IsActive = true;
Window.Current.SizeChanged += Current_SizeChanged;
Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
this.NavigationCacheMode = NavigationCacheMode.Required;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
string caption = "Stop music and exit?";
string message = "If you want to continue listen music while doing other stuff, please use Home key instead of Back key. Do you still want to exit?";
e.Cancel = MessageBoxResult.Cancel == MessageBox.Show(message, caption, MessageBoxButton.OKCancel);
base.OnBackKeyPress(e);
}
答案 0 :(得分:18)
通过Windows.Phone.UI.Input命名空间判断,您的目标是基于WinRT XAML的应用程序,而不是Silverlight WP8.1 在WinRT中没有MessageBox.Show()方法 您必须使用MessageDialog类 加分是您可以自定义对话框上按钮的名称,并且该过程现在是异步的,这意味着它会在显示消息对话框时阻止您的应用程序运行
using Windows.UI.Popups;
...
MessageDialog dialogbox= new MessageDialog("Your message content", "title");
await dialogbox.ShowAsync();
JayDev的回答是完整和正确的
JayDev回答的一个问题是没有"覆盖onBackKeyPress"在WinRT中。 这就是你要做的事情:
using Windows.Phone.UI.Input
...
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//This should be written here rather than the contructor
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
//This is where all your 'override backkey' code goes
//You can put message dialog and/or cancel the back key using e.Handled = true;
}
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
//remove the handler before you leave!
HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
}
答案 1 :(得分:2)
您需要使用MessageDialog而不是MessageBox。即
MessageDialog message = new MessageDialog("my message");
message.ShowAsync();
MessageDialog位于Windows.UI.Popups命名空间中。
具体到您可以使用的方案。
protected async override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
string caption = "Stop music and exit?";
string message = "If you want to continue listen music while doing other stuff, please use Home key instead of Back key. Do you still want to exit?";
MessageDialog msgDialog = new MessageDialog(message, caption);
//OK Button
UICommand okBtn = new UICommand("OK");
msgDialog.Commands.Add(okBtn);
//Cancel Button
UICommand cancelBtn = new UICommand("Cancel");
cancelBtn.Invoked = (s) => { e.Cancel = true; };
msgDialog.Commands.Add(cancelBtn);
//Show message
await msgDialog.ShowAsync();
base.OnBackKeyPress(e);
}
答案 2 :(得分:-2)
试试这个:
MessageBoxResult res= MessageBox.Show(message,caption, MessageBoxButton.OKCancel);
if (res == MessageBoxResult.OK)
{
//Do Action
}
else
{
//Do Action
}