2017-07-26 87 views
0

我有一個按鈕附加到視圖模型中的命令。此按鈕刪除當前在列表視圖中選擇的行,所以我想在繼續之前顯示確認消息框。用戶單擊確定按鈕(在消息框中),然後執行命令,否則,如果用戶單擊取消按鈕命令附加沒有被調用。可能嗎?如果是這樣如何?MVVM顯示確認消息框,然後執行附加到按鈕的命令

<Button Name="btnDelete" Command="{Binding DeleteRowsCommand}"/> 

另一種可能性是調用點擊中通過屬性視圖模型附加到放置在視圖中的自定義消息框的命令,讓這個自定義的消息框可見當屬性的值是true 。但是,我怎樣才能發回視圖模型哪個按鈕'好'或'取消'已被按下?

+0

您的方法乏味但不好。嘗試一些消息框 – Ramankingdom

+0

在'Click'的eventHandler中使用'MessageBox',然後使用ViewModel中的Command並像vm.DeleteRowsCommand.Execute(someObjectIfYouNeedIt)那樣執行它。 – XAMlMAX

回答

1

只需用一個MessageBox

在其路由到DeleteRowsCommand使用這種

var result = MessageBox.Show("message", "caption", MessageBoxButton.YesNo, MessageBoxImage.Question); 

if (result == MessageBoxResult.Yes) 
{ 
    //your logic 
} 

看一看MessageBox Class更多信息的方法。

+3

這會將PresentationFramework.dll添加到ViewModel程序集,我們不想知道關於VM中的Views的任何信息。 – XAMlMAX

+0

@XAMlMAX是的,這將顯示從視圖模型'MessageBox',是的,我沒有看到任何問題。在視圖模型中沒有提高'MessageBox'還有其他幾種方法,但說實話:不要使用大錘來打破堅果。如果你想用'MessageBox'測試代碼,你應該把這段代碼放在一個帶有接口的類中,以便在測試中模擬它。 –

+0

使用事件處理程序進行Click事件以顯示「MessageBox」不一定意味着使用大錘來破解螺母。 – XAMlMAX

0

這樣做的一種可能(也是我認爲最乾淨的)方法是實現像DialogService這樣的服務,將其注入ViewModel並在命令執行時調用它。通過這樣做,您可以將視圖和應用程序邏輯分開,以便ViewModel完全不知道實際顯示對話的方式,並將所有工作委託給該服務。這是一個例子。

首先創建一個對話框的服務,負責顯示對話框,並返回其結果的所有工作:

public interface IDialogService 
{ 
    bool ConfirmDialog(string message); 
} 

public bool ConfirmDialog(string message) 
{ 
    MessageBoxResult result = MessageBox.Show(message, "Confirm", MessageBoxButton.YesNo, MessageBoxImage.Question); 
    return result == MessageBoxResult.Yes ? true : false; 
} 

然後你讓你的視圖模型依賴於服務和inject它在視圖模型:

public class MyViewModel : ViewModelBase 
{ 
    private readonly IDialogService _dialogService; 

    public MyViewModel(IDialogService dialogService) 
    { 
     _dialogService = dialogService; 
    } 
} 

最後,在您的命令中,您可以在命令中調用服務以檢查用戶是否確定要刪除記錄:

public Command DeleteRecordsCommand 
{ 
    get 
    { 
     if (_deleteRecordsCommand == null) 
     { 
      _deleteRecordsCommand = new Command(
       () => 
       { 
        if (_dialogService.ConfirmDialog("Delete records?")) 
        { 
         // delete records 
        } 
       } 
      ); 
     } 

     return _deleteRecordsCommand; 
    } 
}