无法在ShowMessageAsync上使用await

时间:2016-05-19 09:46:09

标签: c# mahapps.metro

我正在使用Mahapp而我正在尝试等待对话框的结果,但是编译器强调了ShowMessageAsync并显示了我:

  

ShowMessageAsync在当前上下文中不存在

这是代码:

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");
    }
}

2 个答案:

答案 0 :(得分:4)

mahapps异步消息框的扩展方法。

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);
    }
}

用法

var res = await InfoBox.ShowMessageAsync(...); 
if (res == MessageDialogResult.Affirmative) 
{ 
     /* Do something*/ 
}

答案 1 :(得分:0)

您必须添加this关键字,因为ShowMessageAsync是一种扩展方法,而不是MetroWindow类的成员。

var result = await this.ShowMessageAsync("Hello!", ...);
                 //^^^^^ here

您还有其他错误。而不是:

 MahApps.Metro.Controls.MessageDialogStyle.AffirmativeAndNegative

使用:

MahApps.Metro.Controls.Dialogs.MessageDialogStyle.AffirmativeAndNegative 

你必须在这些行之前添加等待:

if (result == MessageDialogResult.Affirmative)
{
    await this.ShowMessageAsync("Result", "You said: OK");
   //^^^^ here
}
else
{
    await this.ShowMessageAsync("Result", "You said: CANCEL");
   //^^^^ here
}