简体   繁体   中英

Should I put this function in View (code-behind) or in ViewModel?

I am creating a simple WPF Application. I've a function OpenFile:

private void OpenFile(string fileName)
{
   if(!File.Exists(Helper.GetPath(fileName)))
   {
      MessageBox.Show("Error opening file");
   }
   else
   {
      //Code to handle file opening
   }
}

Ideally where should this function be present? I feel it should be in .xaml.cs because it accesses a MessageBox which comes in the View part. But it also calls my Helper, which is in the model. So I also think it can be in the ViewModel . What is the advantage of having this in the View or in the ViewModel ? Can someone help me with some pointers?

Thanks.

One of the advantages of placing it in the view model would be testability. You could write a unit test that checks that the message box is only displayed if the file exists for example (more accurately it would be an integration test if you are hitting the file system).

However, because you are using a message box directly, your test would never complete on a build server because the machine would be waiting for input from the user whilst the message box is displayed.

Therefore, I would work against an abstraction in your view model, so that you can mock the message box during tests.

This function must be in the ViewModel. You need to create an operation in your view for showing the error message and call this method instead of MessageBox.Show . Showing the message box needs to be done in the View .

Generally you should avoid implementing any business logic inside the View such as validating or handling a file.

If you're using Microsoft Prism you can use the IInteractionRequest interface to have the view create the MessageBox , but actually pass back the necessary response to the view-model.

If you are using Microsoft Prism, then look at how this part works and either simulate it or use a framework that does something similar. 使用Microsoft Prism,那么请查看此部分的工作原理,并模拟它或使用类似的框架。


Basically, that code should go on your view-model for testability, but replace the line where you explicitly call the MessageBox and use the IInteractionRequest mentioned instead.

Here is the documentation pertinent to the scenario you're looking to implement: Chapter 6: Advanced MVVM Scenarios . Look at the section stated User Interaction Patterns .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM