0
votes

I would love to find a simple and MVVM compliant way, to open a new view from the MainWindow.

I have already worked through some instructions and tutorials. But somehow none really worked or it was a mixture of code behind.

I would like to open a view after pressing a button and edit an ObservableCollection in it.

I have already created DataTemplates in App.xaml and mapped the ViewModels with the respective views. But I don't know how to cleanly open a separate window from the MainWindow (MainViewModel) via an ICommand for another ViewModel.

1
I use services. It's a separate dll that exposes Interfaces, you call that from ViewModel or View. It doesn't break MvvM this way.XAMlMAX

1 Answers

1
votes

You should't open a window directly from the MainWindow nor the MainWindowViewModel. But the view model may use a service to open a window:

public class MainWindowViewModel
{
    private readonly IWindowService _service;
    public MainWindowViewModel (IWindowService service)
    {
        _service = service;
    }

    //...
    public void OpenWindowExecuted()
    {
        _service.ShowWindow();
    }
}

Service:

public interface IWindowService
{
    void ShowWindow();
}

public class WindowService : IWindowService
{
    public void ShowWindow();
    {
        Window window = new Window()
        window.Show();
    }
}

You could easily mock out the service in your unit tests.