I’m developing a WPF application with MVVM pattern and I was wondering how can I open and close a window or a dialog from ViewModel or even this is a best practice or not? I mean when it comes to MVVM pattern is always said to avoid code-behind as much as possible so I was thinking should I open and close windows from code-behind or it is OK to do it from the ViewModel. one of the approaches is mentioned is the following one:
1-First define an service like this:
public interface IWindow
{
void Show();
void Close();
bool? ShowDialog();
}
2- Define a BaseWindow class as follow:
public class BaseWindow : Window, IWinodw
{
// Do everything you want
}
3- Derive UI window component from BaseWindow rather than Window
public partial class TestWindow : Window
{
public TestWindow()
{
InitializeComponent();
}
}
4- In your ViewModel define a property like this:
public IWinodw MyWinodw {get; set;}
5- In application startup like app.xaml.cs Inject your UI window to the above property
Now you have full access to your window like opening and closing and…
But some people disagree with the above pattern and they believe this way breaks the MWWM pattern because ViewModel cares about View. now I want to know the best practice for this dilemma and which way is best or how much the mentioned approach is good. all of this stuff is to avoid code-behind obviously. now tell me your idea about this.