不能在 ShowMessageAsync 上使用 await

Can't use await on ShowMessageAsync

我正在使用 Mahapp,我正在尝试等待对话框的结果,但编译器加了下划线 ShowMessageAsync 并显示我:

ShowMessageAsync doesn't exist in the current context

这是代码:

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

您必须添加 this 关键字,因为 ShowMessageAsync 是扩展方法而不是 MetroWindow class.

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

您还有一个错误。而不是:

 MahApps.Metro.Controls.MessageDialogStyle.AffirmativeAndNegative

使用:

MahApps.Metro.Controls.Dialogs.MessageDialogStyle.AffirmativeAndNegative 

并且您必须在这些行之前添加 await:

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

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*/ 
}

添加带有某些操作的按钮的示例:

XAML

 <Button 
            x:Name="btnAddCustomer"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Margin="10" Width="75"
            Click="ButtonAddCustomer_Click">
        <Button.Content>
            <StackPanel Orientation="Horizontal">
                <Image Source="/Images/add.jpg" Height="18"
                       Margin="0 0 5 0"/>
                <TextBlock Text="Add"/>
            </StackPanel>
        </Button.Content>
        
    </Button>

隐藏代码:

private async void ButtonAddCustomer_Click(object sender, RoutedEventArgs e)
    {
        var result =await this.ShowMessageAsync("Title", "Felipe", MessageDialogStyle.AffirmativeAndNegative);
        if (result == MessageDialogResult.Affirmative)
        {
            await this.ShowMessageAsync("Result", "You said: OK");
            //^^^^ here
        }
        else
        {
            await this.ShowMessageAsync("Result", "You said: CANCEL");
            //^^^^ here
        }