2012-06-07 31 views
1

我目前正在開發一個使用mvvm light框架的metro風格的應用程序。如何使用MVVM Light從MessageDialog獲取返回值?

我有一些命令,例如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 

感謝您的幫助! 邁克爾

回答

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-返回async方法通常使用的唯一地方。

相關問題