這樣做的一種可能(也是我認爲最乾淨的)方法是實現像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;
}
}
您的方法乏味但不好。嘗試一些消息框 – Ramankingdom
在'Click'的eventHandler中使用'MessageBox',然後使用ViewModel中的Command並像vm.DeleteRowsCommand.Execute(someObjectIfYouNeedIt)那樣執行它。 – XAMlMAX