What is the correct way to initialize a model and view in WPF CAL MVVM

I came across two ways to initialize Views and ViewModels in MVPM CAL WPF.

1 - It seems to be more popular. You must enable the ViewModel to automatically allow the view. ViewModel contains view information.

    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 - It seems a lot cleaner and removes the View from the ViewModel. You must enable View to automatically enable ViewModel. Embeds objects in a 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 an acceptable method of initializing representations and models and what are the advantages and disadvantages of each method. Should you include objects in your view?

+5
4

, # 1 (, , ). №2 , , , . ( , ).

, # 1 Injection Dependency, # 2 Service Location. , - IoC ( ).

, , , , , # 1 ... IUnityContainer /.

+3

XAML :

<UserControl ...>
    <UserControl.DataContext>
        <local:MyViewModel/>
    </UserControl.DataContext>

    ...

</UserControl>

public partial class MyView : UserControl, IMyView
{
    public MyViewModel ViewModel
    {
        get { return this.DataContext as MyViewModel; }
    }

    ...
}
+2

1 , viewmodel.

viewmodels , . --. , , , , , , .

2 . ioc - . IoC . , . factory.

+1

, 2 , . .

2 , 1, , ViewModel .

, , XML , , .

:

public interface IView
{
}

public interface IViewModel
{
}

public class View : IView
{
    private IViewModel model;

    public View(IViewModel m)
    {
        this.model = m;
        this.DataContext = this.model;
    }
}

public class ViewModel : IViewModel
{
}

:

Container.RegisterType<IViewModel, ViewModel>( /* appropriate container config */ );
Container.RegisterType<IView, View>(/* appropriate container config */ );

:

Container.Resolve<IViewModel>();
+1

All Articles