缺点,不能进行单元测试

比如,用户在界面点击按钮,实现用户选择一个文件,然后对文件内容进行解析。常见错误如下

 1 using microsoft.win32;
 2 
 3 namespace view和viewmodel分工
 4 {
 5     public class mainwindowviewmodel
 6     {
 7         public void parsefile()
 8         {
 9             openfiledialog openfiledialog = new openfiledialog();
10             if (openfiledialog.showdialog() == true)
11             {
12                 //解析文件
13             }
14         }
15     }
16 }

和用户交互的部分(openfiledialog),应该放在view中。这里可以利用命令参数来传递文件名

 1 namespace view和viewmodel分工
 2 {
 3     public class mainwindowviewmodel
 4     {
 5         public void parsefile(string filename)
 6         {
 7             //解析文件
 8         }
 9     }
10 }

在view中按钮的单击事件中,进行交互。如果用户取消了操作,利用异常取消命令执行

1         private void button_click(object sender, routedeventargs e)
2         {
3             openfiledialog openfiledialog = new openfiledialog();
4             if (sender is button button && openfiledialog.showdialog() == true)
5                 button.commandparameter = openfiledialog.filename;
6             else
7                 throw new usercanceledexception();
8         }

在xaml部分,按钮同时指定click和command

        <button command="{binding parsefilecommand}" click="button_click" content="选择一个文件解析"/>

完整示例在我的github中

推荐当我们使用 mvvm 模式时,我们究竟在每一层里做些什么?