这样做的一种可能(也是我认为最干净的)方法是实现像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