Can't use await on ShowMessageAsync

风流意气都作罢 提交于 2019-12-07 13:24:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!