我想在我的 ViewModel 中使用 SaveFileDialog,但是由于从 ViewModel 绑定(bind)到 View 是不正确的,我搜索了一些方法要做到这一点。但是我发现了一些没有完全分离 View 形式 ViewModel 的答案,像这样:
public interface IOService
{
void IMessageBox(string Message);
string ISaveFileDialog(string DefaultPath);
}
public class IDialog : IOService
{
public void IMessageBox(string Message)
{
System.Windows.MessageBox.Show(Message);
}
public string ISaveFileDialog(string DefaultPath)
{
System.Windows.Forms.SaveFileDialog dg = new SaveFileDialog
{
InitialDirectory = DefaultPath,
Filter = "PDF files (*.pdf) | *.pdf"
};
dg.ShowDialog();
if (dg.FileName == null)
dg.FileName = string.Empty;
return dg.FileName;
}
}
他们说,这是一个Service,使用它会把View和ViewModel分开。但是我们在 ViewModel 中从中创建了一个Instance:
IDialog iDialog = new IDialog();
所以我想知道,这种方法与直接从 ViewModel 调用 MessageBox 或 SaveFileDialog 有什么区别?
注意:我还发现一些东西说我可以使用像上面这样的服务,但要像这样实现它:
public class ExportViewModel : BaseViewModel
{
IOService _IOService;
public ExportViewModel(IOService ioservice)
{
_IOService = ioservice;
.
.
}
}
但我不知道如何将 IOService 作为参数发送到 ExportViewModel(因为我们无法从创建实例一个接口(interface)!)
最佳答案
您不应该直接从 VM 中弹出对话框以实现自动化测试。
如果您调用 MessageBox.Show(),您的测试将卡住,直到有人关闭对话框。
如果相反,您使用“IMessageBox”进行单元测试,您可以注入(inject)一个实际上不显示对话框但返回特定值(结果)的实现。
关于c# - (WPF/MVVM) Service 和 ViewModel 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39254823/