Home > Software design >  WPF - Should OpenFileDialog be in the ViewModel
WPF - Should OpenFileDialog be in the ViewModel

Time:04-10

I have a VERY SIMPLE application which is supposed to read a file selected by the user and display it on the screen. For that I created two views, one with a button for the user to select the file and another view for displaying the contents of the file.

I also have two ViewModels one for each of the views, now, when the user clicks the button to select a file the code in the ViewModel will use OpenFileDialog and open the file, my question is should I call OpenFileDialog from the viewModel or from the Model for a MVVM project?

CodePudding user response:

Dialog boxes don't fit into the MVVM paradigm very well, due to the tight coupling they have with the OS. As a general rule though, anything you want directly unit-tested belongs in the view model, while anything that creates Windows GUI objects at runtime belongs in your view layer. With that in mind, the view is the appropriate layer for calling OpenFileDialog. You may find that you still need to break the clean MVVM architecture to do this, so abstracting it away into a service that can be injected will at least keep it away from the rest of your code and maintain good seperation of concerns.

If you really want to do this properly then you have to implement some boiler-plate code similar to what the WPF team wrote for "regular" windows. I wrote a long article about it here, along with a library for easily adding dialog box functionality to your own MVVM projects:

https://www.codeproject.com/Articles/820324/Implementing-Dialog-Boxes-in-MVVM

  • Related