有几种方法可以解决这个问题。
最简单的就是MessageBox.Show
在您的视图模型中使用。这易于编码且易于理解。它还破坏了您对视图模型进行单元测试的能力,因为现在它的行为是阻塞并等待用户输入。
复杂性链的下一步是为视图模型定义一个接口,以便在需要询问是或否问题时使用。例如:
public interface IConfirmationDialogService
{
bool Show(string question);
}
然后您的视图模型实现一个属性:
public IConfirmationDialogService ConfirmationDialogService { get; set; }
当视图模型在您的应用程序中时,您实现了一个服务类供视图模型使用:
public class ViewConfirmationDialogService : IConfirmationDialogService
{
public string Caption { get; set; }
public bool Show(string question)
{
return MessageBox.Show(
string question,
Caption,
MessageBoxButtons.YesNo,
MessageBoxImage.Question) == MessageBoxResult.Yes;
}
}
现在在您的视图模型中的任何地方,您都可以从用户那里得到确认:
if (!ConfirmationDialogService.Show("Do you want to do this?"))
{
return;
}
你如何对此进行单元测试?带着嘲讽。在您的单元测试中,您实现了一个模拟用户输入的类:
public class MockConfirmationDialogService : IConfirmationDialogService
{
public MockConfirmationDialogService(bool result)
{
_Result = result;
}
private bool _Result;
public bool Show(string question)
{
return _Result;
}
}
这样您就可以测试等待用户输入的方法,例如:
MyViewModel vm = new MyViewModel()
ConfirmationDialogService = new MockConfirmationDialogService(false);
vm.ExecuteCommand();
Assert.IsFalse(vm.CommandChangedSomething);
vm.ConfirmationDialogService = new MockConfirmationDialogService(true);
vm.ExecuteCommand();
Assert.IsTrue(vm.CommandChangedSomething);
复杂性的下一步是当您意识到这只是您将在视图模型中实现对话框的众多问题之一,而不是有一个IConfirmationDialogService
是或否的问题,您将需要一个更强大的对话服务来处理各种对话。到那时,您将顺利实现自己的视图模型框架,您应该开始查看现有的视图模型框架,看看它们是如何做到的。