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

I am creating a simple WPF application. I have an OpenFile function:

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 feature be present? I feel it should be in .xaml.cs because it accesses the MessageBox, which is part of the View . But he also calls my assistant, who is in the model. Therefore, I also think it could be in the ViewModel . What is the advantage of this in View or in ViewModel ? Can someone help me with some pointers?

Thanks.

+6
source share
3 answers

One of the advantages of placing it in a view model is validation. You can write unit test, which checks that the message box is only displayed if the file exists, for example (more precisely, it will be an integration test if you click on the file system).

However, since you use the message box directly, your test will never end on the build server because the machine will wait for input from the user while the message box is displayed.

So I would work against abstraction in your view model so that you can make fun of the message box during tests.

+7
source

This function must be in the ViewModel. You need to create an operation in your view to display the error message and call this method instead of MessageBox.Show . The display of the message box should be in View .

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

+7
source

If you are using Microsoft Prism, you can use the IInteractionRequest interface to create a MessageBox view, but in fact go through return the necessary response to the view model.

If you use not with Microsoft Prism, see how this part works, either simulate it, or use a framework that does something similar.


Basically, this code should be included in your view model for verification, but replace the line where you explicitly call MessageBox and use IInteractionRequest instead.

Here is the documentation related to the script you want to implement: Chapter 6: Advanced MVVM Scripts . See the section listed in User Interaction Templates .

+2
source

Source: https://habr.com/ru/post/909923/


All Articles