问题
I'm using Mahapp and I'm trying to wait for the result of the dialog, but the compiler underlined ShowMessageAsync
and display me:
ShowMessageAsync doesn't exist in the current context
this is the code:
private async void ShowMessageBox(object sender, RoutedEventArgs e)
{
var result = await ShowMessageAsync("Hello!", "Welcome to the world of metro!",
MahApps.Metro.Controls.MessageDialogStyle.AffirmativeAndNegative);
if (result == MessageDialogResult.Affirmative)
{
this.ShowMessageAsync("Result", "You said: OK");
}
else
{
this.ShowMessageAsync("Result", "You said: CANCEL");
}
}
回答1:
Extension method for mahapps async message box.
using System.Windows;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System.Threading.Tasks;
public static class InfoBox
{
public async static Task<MessageDialogResult> ShowMessageAsync(string title, string Message, MessageDialogStyle style = MessageDialogStyle.Affirmative, MetroDialogSettings settings = null)
{
return await ((MetroWindow)(Application.Current.MainWindow)).ShowMessageAsync(title, Message, style, settings);
}
}
Usage
var res = await InfoBox.ShowMessageAsync(...);
if (res == MessageDialogResult.Affirmative)
{
/* Do something*/
}
回答2:
You must add the this
keyword because the ShowMessageAsync
is an extension method and not a member of the MetroWindow
class.
var result = await this.ShowMessageAsync("Hello!", ...);
//^^^^^ here
You have another error. Instead of:
MahApps.Metro.Controls.MessageDialogStyle.AffirmativeAndNegative
Use:
MahApps.Metro.Controls.Dialogs.MessageDialogStyle.AffirmativeAndNegative
And you must add await before these lines:
if (result == MessageDialogResult.Affirmative)
{
await this.ShowMessageAsync("Result", "You said: OK");
//^^^^ here
}
else
{
await this.ShowMessageAsync("Result", "You said: CANCEL");
//^^^^ here
}
来源:https://stackoverflow.com/questions/37319540/cant-use-await-on-showmessageasync