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.