【问题标题】:How can I get a return value from a MessageDialog using MVVM Light?如何使用 MVVM Light 从 MessageDialog 获取返回值?
【发布时间】:2012-06-07 23:35:12
【问题描述】:

我目前使用 mvvm light 框架开发 Metro 风格的应用程序。

我有一些命令,例如DeleteSelectedAppUserCommand。用户必须确认他确实想要删除该用户。所以我在静态类“DialogService”中写了一个静态方法“ShowMessageBoxYesNo”。

public static async Task<bool> ShowMessageBoxYesNo(string message, string title)
{
    MessageDialog dlg = new MessageDialog(message, title);

    // Add commands and set their command ids
    dlg.Commands.Add(new UICommand("Yes", null, 0));
    dlg.Commands.Add(new UICommand("No", null, 1));

    // Set the command that will be invoked by default
    dlg.DefaultCommandIndex = 1;

    // Show the message dialog and get the event that was invoked via the async operator
    IUICommand result = await dlg.ShowAsync();

    return (int)result.Id == 0;
}

在命令中我想调用这个方法,但我不知道如何...... 这不可能吗?以下代码不起作用!

#region DeleteSelectedAppUserCommand

/// <summary>
/// The <see cref="DeleteSelectedAppUserCommand" /> RelayCommand's name.
/// </summary>
private RelayCommand _deleteSelectedAppUserCommand;

/// <summary>
/// Gets the DeleteSelectedAppUserCommand RelayCommand.
/// </summary>
public RelayCommand DeleteSelectedAppUserCommand
{
    get
    {
        return _deleteSelectedAppUserCommand
            ?? (_deleteSelectedAppUserCommand = new RelayCommand(
            () =>
            {
                if (await DialogService.ShowMessageBoxYesNo("Do you really want delete the user?","Confirm delete")
                {
                    AppUsers.Remove(SelectedEditAppUser);
                }
            },
            () =>
                this.SelectedEditAppUser != null
            ));
    }
}
#endregion

感谢您的帮助! 迈克尔

【问题讨论】:

    标签: .net mvvm-light windows-8 microsoft-metro async-await


    【解决方案1】:

    如果您想在 lambda 中使用 await,则必须将该 lambda 标记为 async

    new RelayCommand(
        async () =>
        {
            if (await DialogService.ShowMessageBoxYesNo("Do you really want delete the user?", "Confirm delete")
            {
                AppUsers.Remove(SelectedEditAppUser);
            }
        },
        () =>
            this.SelectedEditAppUser != null
        )
    

    这会创建一个 void-returning async 方法,通常应该避免这种方法。但我认为这很有意义,因为您基本上是在实现一个事件处理程序。而事件处理程序是唯一可以正常使用void-returning async 方法的地方。

    【讨论】:

      猜你喜欢
      • 2012-07-11
      • 2013-08-09
      • 2016-04-04
      • 2013-05-31
      • 2011-12-23
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2013-03-21
      相关资源
      最近更新 更多