I have come accross two ways of initializing Views and ViewModels in WPF CAL MVVM.
1 - Seems to be more popular. Requires you to resolve the ViewModel to automatically resolve the View. The ViewModel contains information about the View.
public interface IView
{
void SetModel(IViewModel model);
}
public interface IViewModel
{
IView View { get; }
}
public class View
{
public void SetModel(IViewModel model)
{
this.DataContext = model;
}
}
public class ViewModel
{
private IView view;
public ViewModel(IView view)
{
this.view = view;
}
public IView View { return this.view; }
}
2 - Seems a lot cleaner and removes the View from the ViewModel. Requires you to resolve the View to automatically resolve the ViewModel. Injects objects into the view (Not sure if this is good or not).
public interface IView
{
}
public interface IViewModel
{
}
public class View
{
private IViewModel model;
public View(IUnityContainer unityContainer)
{
this.model = unityContainer.Resolve<IViewModel>();
this.DataContext = this.model;
}
}
public class ViewModel
{
}
What is the accepted method of initializing the views and models and what are the advantages and disadvantages of each method. Should you be injecting objects into your view?