Question

I currently develop a metro style app using mvvm light framework.

I have some commands, e.g. DeleteSelectedAppUserCommand. The user must confirm that he really wants to delete the user. So I have written a static Method "ShowMessageBoxYesNo" in the static class "DialogService".

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

In the command I want call this method, but I don't know how... Is this not possible? Following code doesn't work!

#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

Thanks for help! Michael

Was it helpful?

Solution

If you want to use await in a lambda, you have to mark that lambda as async:

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

This creates a void-returning async method which should be usually avoided. But I think it makes sense here, because you're basically implementing an event handler. And event handlers are the only place where void-returning async methods are normally used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top