steve
steve

Reputation: 917

Getting around circular dependency

Could I get help with a little issue I am encountering regarding splitting projects into different tiers. In my ViewModel logic I have code where I create a new instance of a window when a button is clicked (I use ICommand interface for that)

The problem is however, that this requires my View folder which is in the presentation layer, I can’t reach it as my presentation layer is dependent on my ViewModel in the logic layer.

I would just move the code that deals with the creation of the pages to the view code behind but I also pass the current instance of a viewmodel as a parameter for that new window being created (for eventhandling purposes).

Any help is much appreciated! Thanks.

Upvotes: 0

Views: 214

Answers (1)

mm8
mm8

Reputation: 169200

A view model shouldn't create instances of windows. What you could do is to inject your view model with a service that is responsible for creating windows, e.g.:

public class MainWindowViewModel
{
    private readonly IWindowService _windowService;

    public MainWindowViewModel(IWindowService windowService)
    {
        _windowService = windowService;
        CreateWindowCommand = new DelegateCommand(() =>
        {
            _windowService.CreateWindow(new SomeViewModel());
        });
    }

    public ICommand CreateWindowCommand { get; }
}

Define the IWindowService interface in the view model project and the concrete implementation of it in the view/presentation project:

public class WindowService : IWindowService
{
    public void CreateWindow(SomeViewModel vm)
    {
        Window win = new Window();
        win.DataContext = vm;
        win.Show();
    }
}

Upvotes: 3

Related Questions