开发者

Set the DataContext of a ViewModel in MVVMLight

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 commu开发者_运维问答nicate between the ViewModels? Thanks for your advices.

Regards, pro


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜