c# - (WPF/MVVM) Service 和 ViewModel 有什么区别?

标签 c# wpf mvvm service interface

我想在我的 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,使用它会把ViewViewModel分开。但是我们在 ViewModel 中从中创建了一个Instance:

IDialog iDialog = new IDialog();

所以我想知道,这种方法与直接从 ViewModel 调用 MessageBoxSaveFileDialog 有什么区别?

注意:我还发现一些东西说我可以使用像上面这样的服务,但要像这样实现它:

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/

相关文章:

c# - 请求的地址在 TCP 套接字通信的上下文中无效

c# - 具有类似 WPF 的 GUI 创建的多平台编程语言?

C# WPF 单选按钮拆分到不同的页面

wpf - 如果元素不支持命令,是否有任何通用程序在 MVVM 中实现命令?

wpf - 使用 Prism 激活/停用工具栏按钮

c# - 嵌套 for 循环 : giving concatenated result

c# - 如何在 C# 中使用 Magento 2 API 创建 REST 请求?

c# - 桌面应用程序的多个 Google 访问权限

c# - 多个窗口导航相同的数据集合

c# - 在 MVVM 中使用委托(delegate)更新 ObservableCollection?