Set the DataContext of a ViewModel in MVVMLight

北城以北 提交于 2020-01-06 20:14:58

问题


I've got a question of the MVVM-Pattern. So I'm not sure, that I've had understand it completely.

My scenario:

  • ViewModelLocator : Provide the requested ViewModel to a specified view.
  • LoginViewModel: ViewModel for the LoginView
  • MainPageViewModel: ViewModel for the MainPageView

My example app. is simple: The user can login and comes to the MainPageView.

The MainPageView uses the MainPageViewModel. I use the messenger of the MVVMLight framework to navigate from the LoginView to the MainPageView.

 Messenger.Default.Register<LoginPerson>(this, Constants.NavigateLogin,
                person => this.Window.SetContentControl(new MainPage(person)));

I pass the loggedin person to the View. The MainPage - View will set the the logged in person to its ViewModel (=> MainPageViewModel).

Is this way correct? I don't think so :-) How can I communicate between the ViewModels? Thanks for your advices.

Regards, pro


回答1:


When using MVVM, your application is your ViewModels, not your Views. You should not be handling any kind of business logic such as navigation or passing User objects around from your Views. The View is simply a pretty layer that allows the user's to interact with your ViewModels easily.

Usually in this kind of situation I use a ShellViewModel which contains a CurrentPage property that is set to whatever ViewModel is the CurrentPage. I would store a CurrentUser property in the ShellViewModel as well.

Your ShellViewModel is your startup object, and on startup the CurrentPage would be a LoginViewModel. When the user successfully logs in, the LoginViewModel broadcasts a LoginSuccessful message with a parameter of the CurrentUser, and the ShellViewModel would pickup that message and set the CurrentUser based on the message parameters, and would switch CurrentView to a new MainPageViewModel

For an example, check out my post here



来源:https://stackoverflow.com/questions/7571297/set-the-datacontext-of-a-viewmodel-in-mvvmlight

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!