how to load wpf usercontrol in MVVM pattern

前端 未结 6 1739
刺人心
刺人心 2021-02-06 12:36

I\'m creating a wpf user control which is in mvvm pattern. So we have : view(with no code in codebehind file), viewmodel,model,dataaccess files.

I have MainWindo

6条回答
  •  忘了有多久
    2021-02-06 13:01

    There are endless ways to do it, wich all fall in one of the two categories:"view first" or "model first".

    In a "view first" mode the view (e.g. your mainwindow) is created first and then (e.g. in the codebehind) the View instantiates the ViewModel and sets it as its datacontext):

    private void WindowLoaded(object sender, EventArgs args)
    {
       this.DataContext = ViewModelService.GetViewModelX();
    }
    

    In a "model first" mode the ViewModel is there first and then instanciated the View.

    // method of the viewmodel 
    public void LoadView()
    {
         // in this example the view abstracted using an interface
         this.View = ViewService.GetViewX();
         this.View.SetDataContext(this);
         this.View.Show();    
    }
    

    The examples given here are just one way of many. You could look at the various MVVM frameworks and see how they do it.

提交回复
热议问题