I've been wondering about this for a while... What's the best practice for opening a new window (view & viewmodel) from another viewmodel IF we keep in mind that the viewmodel which opens the new window is not aware of the existence of that view (as it should be).
Thanks.
I prefer to use an action delegate that is inserted via the ViewModel constructor. this also means we can easily verify during unit-testing:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = new MainViewModel(() => (new Window()).Show()); // would be actual window
}
}
public class MainViewModel
{
private Action popupAction;
public MainViewModel(Action popupAction)
{
this.popupAction = popupAction;
}
public ICommand PopupCommand { get; set; }
public void PopupCommandAction()
{
popupAction();
}
}
public class SomeUnitTest
{
public void TestVM()
{
var vm = new MainViewModel(() => { });
}
}
I don't use the ViewModel to open another View/ViewModel. This is in the responsibility of a Controller. The ViewModel can inform the Controller (e.g. via Event) that the user expects to see the next View. The Controller creates the View/ViewModel with the help of an IoC Container.
How this works is shown in the ViewModel (EmailClient) sample application of the WPF Application Framework (WAF).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With