MVVM show new window from VM when seperated projects

  • Define the IWindowService interface in the model project.
  • Reference the model project from the view model project.
  • Implement the IWindowService in the WPF application (view) project.

The button should then be bound to an ICommand that uses IWindowService to open the window. Something like this:

public class MainWindowViewModel
{
    private readonly IWindowService _windowService;

    public MainWindowViewModel(IWindowService windowService)
    {
        _windowService = windowService;
        AddProfile = new DelegateCommand(() =>
        {
            _windowService.OpenProfileWindow(new AddProfileViewModel());
        });
    }

    public ICommand AddProfile { get; }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel(new WindowService());
    }
}

public class WindowService : IWindowService
{
    public void OpenProfileWindow(AddProfileViewModel vm)
    {
        AddProfileWindow win = new AddProfileWindow();
        win.DataContext = vm;
        win.Show();
    }
}